AJAX如何调用TWIG

我试图了解Twig如何通过AJAX加载模板。 从他们的网站上可以看出如何加载模板(http://twig.sensiolabs.org/doc/api.html)

echo $twig->render('index.html', array('the' => 'variables', 'go' => 'here')); 

但是这对AJAX调用有什么用呢? 你怎么告诉Twig你想要’渲染’只是index.html的一部分的东西……而不是重新加载整个页面? 我查看了Twig唯一的Ajax示例(http://twig.sensiolabs.org/doc/recipes.html),但这并未解释Twig如何知道您要更改的页面的哪个部分。 假设您的Ajax调用导致页面内容更新。 我只需要一个简单的例子,比Twig的食谱页面更多。

有几种方法可以实现这一目标:

1)在index.html和content.html等几个文件中分隔index.html。 然后在index.html中使用include函数来包含content.html。

示例:

 if(isAjaxRequest()) //try to find the right function here echo $twig->render('content.html', array('the' => 'variables', 'go' => 'here')) else echo $twig->render('index.html', array('the' => 'variables', 'go' => 'here')); 

编辑:如果您使用jQuery执行ajax请求,例如:

 $.get('yoururl', function(data) { $('#divtoremplace').html(data); }); 

2)在index.html中使用request.ajax boolean

 {% if request.ajax == false %} 

My header, not reloaded with ajax

{% endif %}

My content, reloaded with ajax

{% if request.ajax == false %}

Other content, not reloaded with ajax

{% endif %}

不确定第二个,但这应该做文件的技巧。 最好的方法是第一个解决方案,将代码分开。

直接在模板中:

 {% if app.request.isXmlHttpRequest() %} // code if ajax request {% else %} // code if not ajax request {% endif %}