AJAX呼叫如何与TWIG一起使用 [英] How AJAX calls work with TWIG

查看:83
本文介绍了AJAX呼叫如何与TWIG一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解Twig如何通过AJAX加载模板. 在他们的网站上,很清楚如何加载模板(http://twig.sensiolabs.org/doc/api.html)

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)

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食谱页面上的内容还要多.

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.

推荐答案

有几种方法可以实现:

1)将index.html分成几个文件,例如index.html和content.html. 然后在index.html中使用 include 函数包含content.html.

1) Separate your index.html in several files like index.html and content.html. Then use include function in index.html to 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请求:

Edit : If you do your ajax request with jQuery for example :

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

2)在index.html中使用request.ajax布尔值

2) Use the request.ajax boolean in your 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.

这篇关于AJAX呼叫如何与TWIG一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆