[英]Modify twig variable through js without reloading page
I have an array of objects which are rendered through for loop in twig template.我有一个对象数组,这些对象通过 twig 模板中的 for 循环呈现。 I want to apply a filter-like mechanism where after selecting a category from a filter, list of elements in twig would update without refreshing a page and contain elements only from chosen category.
我想应用一个类似过滤器的机制,在从过滤器中选择一个类别后,twig 中的元素列表将在不刷新页面的情况下更新,并且仅包含来自所选类别的元素。
Until now I managed to pass chosen category value through ajax to Symfony controller, parse it, encode to JS and send it as a response and fetch it via ajax.到目前为止,我设法将所选类别值通过 ajax 传递给 Symfony controller,解析它,编码为 JS 并将其作为响应发送并通过 ajax 获取它。
Here's some code:这是一些代码:
//variable passed to twig
return $this->render('@Ad/ad_list.html.twig', [
'adList' => $adList,
]);
//An ajax call
$.ajax({
url : $form.attr('action'),
type: "POST",
data : filters,
complete: function(html) {
console.log(html['responseJSON'])
}
});
//creating a response
$response = JsonResponse::fromJsonString($jsonContent);
$response->prepare($request);
$response->send();
{% for ad in adList|slice(0, 9) %}
...
{% endfor %}
Is it possible to update passed variable ($adList) to twig via JS, so it would render elements from response?是否可以通过 JS 将传递的变量($adList)更新为 twig,以便从响应中呈现元素?
Thanks to brombeer and DarkBee help I achieved my goal.感谢 brombeer 和 DarkBee 的帮助,我实现了我的目标。 I did it by:
我是这样做的:
main template:主模板:
<section>
{% include '@Ad/ad_list_container.html.twig' %}
</section>
ad_list_container template: ad_list_container 模板:
<div id="ad-list">
{% for ad in adList %}
...
{% endfor %}
</div>
ajax call: ajax 拨打:
$.ajax({
url : $form.attr('action'),
type: "POST",
data : filters,
success: function(response) {
$('#ad-list').html(response);
}
});
php controller: php controller:
return $this->render('@Ad/ad_list_container.html.twig', [
'adList' => $adList
]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.