php AJAX 调用如何与 TWIG 配合使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14154670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How AJAX calls work with TWIG
提问by user1082428
I am trying to understand how Twig can load a template through AJAX. From their website, it is clear how to load a template (http://twig.sensiolabs.org/doc/api.html)
我试图了解 Twig 如何通过 AJAX 加载模板。从他们的网站上,很清楚如何加载模板 (http://twig.sensiolabs.org/doc/api.html)
echo $twig->render('index.html', array('the' => 'variables', 'go' => 'here'));
But how would this work for an AJAX call? How would you tell Twig that you want to 'render' something that is only a part of index.html ... and not reload the entire page? I looked at Twig's sole Ajax example (http://twig.sensiolabs.org/doc/recipes.html), but this doesn't explain how Twig knows what part of the page you want to change. Assuming your Ajax call results in page content updates. I just need a simple example of this, something more than what is on Twig's recipe page.
但这对 AJAX 调用有何作用?你如何告诉 Twig 你想“渲染”一些只是 index.html 一部分的东西......而不是重新加载整个页面?我查看了 Twig 唯一的 Ajax 示例 (http://twig.sensiolabs.org/doc/recipes.html),但这并没有解释 Twig 如何知道您想要更改页面的哪个部分。假设您的 Ajax 调用导致页面内容更新。我只需要一个简单的例子,比 Twig 的食谱页面上的更多。
采纳答案by Pierrickouw
There are several ways to accomplish that :
有几种方法可以实现:
1) Separate your index.html in several files like index.html and content.html. Then use includefunction in index.html to include content.html.
1) 将您的 index.html 分成几个文件,例如 index.html 和 content.html。然后在 index.html 中使用include函数来包含 content.html。
Example :
例子 :
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'));
Edit :If you do your ajax request with jQuery for example :
编辑:如果您使用 jQuery 执行 ajax 请求,例如:
$.get('yoururl', function(data) {
$('#divtoremplace').html(data);
});
2) Use the request.ajaxboolean in your index.html
2)request.ajax在 index.html 中使用布尔值
{% 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 %}
Not sure about the second one, but this should do the trick accordind to the documentation. The best way is the first solution, separate your code.
不确定第二个,但这应该可以根据文档进行操作。最好的方法是第一个解决方案,将您的代码分开。
回答by Mick
Directly in the template:
直接在模板中:
{% if app.request.isXmlHttpRequest() %}
// code if ajax request
{% else %}
// code if not ajax request
{% endif %}

