I have an array of objects which are rendered through for loop in twig template. 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.
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.
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?
CodePudding user response:
Thanks to brombeer and DarkBee help I achieved my goal. I did it by:
- Creating new template which holds list of elements,
- Rendering this new template in main template and passing there updated value
main template:
<section>
{% include '@Ad/ad_list_container.html.twig' %}
</section>
ad_list_container template:
<div id="ad-list">
{% for ad in adList %}
...
{% endfor %}
</div>
ajax call:
$.ajax({
url : $form.attr('action'),
type: "POST",
data : filters,
success: function(response) {
$('#ad-list').html(response);
}
});
php controller:
return $this->render('@Ad/ad_list_container.html.twig', [
'adList' => $adList
]);