我不确定我的标题是否准确,所以我会尽力在这里解释。
我试图尝试做的是用Ajax调用我的控制器并让它更改页面上的内容而不重新加载(内容由块定义)。因此,对于一个松散的例子,在主页到达时,主页的内容将是:
# routing.yml
StackQuestionBundle_osgs_home:
pattern: /
defaults: { _controller: StackQuestionBundle:Pages:index }
options:
expose: true
StackQuestionBundle_osgs_page:
pattern: /page
defaults: { _controller: StackQuestionBundle:Pages:page }
options:
expose: true
<!-- @StackQuestionBundle:Pages:index.html.twig -->
<header>
{% block title %} <!-- Title --> {% endblock %}
<nav> </nav>
</header>
<main>
<aside> <!-- Sidebar --> </aside>
<section>
{% block content %} <!-- Main Content -->{% endblock %}
</section>
</main>
<footer>
{% block footer %} <!-- content --> {% endblock %}
<nav> </nav>
</footer>
// JS
$('nav button.test').click(function() {
$.ajax({
url: "{{ path('OSGSBundle_osgs_page') }}",
type: "POST",
success: function(data) {
//Change the content in the blocks!
//alert("It worked!")
}
});
});
# PagesController.php
namespace MyNameSpace\StackQuestionBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
class PagesController extends Controller
{
public function indexAction()
{
return $this->render('OSGSBundle:Pages:index.html.twig');
}
public function pageAction(Request $request)
{
$isAjax = $this->get('Request')->isXMLHttpRequest();
if ($isAjax)
{
// Replace/Append the content in index.html.twig with the content from page.html.twig
}
else
{
// Load page normally if navigated to http://localhost/page
return $this->render('OSGSBundle:Pages:page.html.twig');
}
}
}
这是我目前的代码。到目前为止,我已经设法仅根据DOM元素替换数据。因此,我会替换<main>
标记中的所有信息。我只想替换我的Twig块标签中的内容。旁注:我正在使用FOSJSRoutingBundle来更改URL。
在此先感谢,我感谢您的帮助/建议。我希望这不会太混乱。
答案 0 :(得分:1)
1)为您的块添加一个新的twig文件:myblock.html.twig
2)更新您的控制器
if ($isAjax)
{
return $this->render('OSGSBundle:Pages:myblock.html.twig');
}
答案 1 :(得分:1)
我想没有通过javascript更改twig块的通用方法,因为javascript是clientside而twig是服务器端。
您必须通过将块包装在div或具有id的任何标记中来手动执行此操作。
<section id="block-content">
{% block content %} <!-- Main Content -->{% endblock %}
</section>
然后,您可以应用正常的ajax行为并在服务器上呈现响应的ajax模板,因为toine指出并使用id更改元素中的内容。