Skip to content Skip to sidebar Skip to footer

Change Twig Template Variable With Ajax

I'am trying to reload a part of my html with a new value that I've got using AJAX. There is a {% for client in clients %} loop, and i've got a new set of clients using AJAX :

Solution 1:

You can't change the value of the clients via AJAX because this template has already been rendered. You could however create a separate twig template like this:

{# loop.html.twig #}
{% for client in clients %}
.. your code
{% endfor %}

Then include it in your template like this:

<div id="client-loop-container">
    {% include 'loop.html.twig' %}
</div>

So in your ajax controller:

$clients=$this->getDoctrine()->getRepository(
        Client::class)->findBy(array('name'=>$search));

$template = $this->render('yourTemplate.html.twig')->getContent();
$response = new JsonResponse();
$response->setStatusCode(200);
return$response->setData(['template' => $template ]); 

Finally in your ajax you should have something like this:

$.ajax({
    type: "POST",
    success: function(response) {
        response = JSON.parse(response);
        $("div#client-loop-container").html(response.template);    
    }
});

Solution 2:

you could not do that because twig is rendered at the server side. you will need to update the HTML generated by {% for client in clients%} using javascript

Solution 3:

in your controller

$clients=$this->getDoctrine()->getRepository(
        Client::class)->findBy(array('name'=>$search));

return$this->render('yourTemplate.html.twig')->getContent();

in your twig

$.ajax({
    type: "POST",
    success: function(data) {

        $("div#client-loop-container").html(data);    
    }
});

Post a Comment for "Change Twig Template Variable With Ajax"