我试图了解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的食谱页面更多.
我想通过点击链接显示带有jquery的数据.这是代码,但缺少一些代码jquery来浏览数据和代码twig来显示它们.
这是Twig:
<a href class="list">List</a>
<div id="travels">
// display data here
</div>
<script>
$(document).ready(function () {
$(".list").click(function () {
$.ajax({
type: 'POST',
dataType: 'json',
url: Routing.generate('travel_list_ajax'),
success: function () {
// rest of code
}
});
return false;
});
});
</script>
Run Code Online (Sandbox Code Playgroud)
行动
public function listAjaxAction(Request $request)
{
if ($request->isXmlHttpRequest()) {
$em = $this->getDoctrine()->getManager();
$travels = $em->getRepository('AppBundle:Travel')->findAll();
$response = new JsonResponse();
return $response->setData(array('travels'=>$travels));
}
return null;
}
Run Code Online (Sandbox Code Playgroud)