AJAX如何调用TWIG

use*_*428 12 php ajax jquery twig

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

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

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

Mic*_*ick 11

直接在模板中:

{% if app.request.isXmlHttpRequest() %}
  // code if ajax request
{% else %}
  // code if not ajax request
{% endif %}
Run Code Online (Sandbox Code Playgroud)


Pie*_*ouw 10

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

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'));
Run Code Online (Sandbox Code Playgroud)

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

$.get('yoururl', function(data) {
  $('#divtoremplace').html(data);
});
Run Code Online (Sandbox Code Playgroud)

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

{% if request.ajax == false %}
<p>My header,  not reloaded with ajax</p>
{% endif %}

<p>My content, reloaded with ajax</p>

{% if request.ajax == false %}
<p>Other content,  not reloaded with ajax</p>
{% endif %}
Run Code Online (Sandbox Code Playgroud)

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