How AJAX calls work with TWIG

前端 未结 2 2060
名媛妹妹
名媛妹妹 2021-02-02 00:42

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)

<         


        
2条回答
  •  无人共我
    2021-02-02 01:04

    There are several ways to accomplish that :

    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.

    Example :

    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'));
    

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

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

    2) Use the request.ajax boolean in your index.html

    {% if request.ajax == false %}
    

    My header, not reloaded with ajax

    {% endif %}

    My content, reloaded with ajax

    {% if request.ajax == false %}

    Other content, not reloaded with ajax

    {% 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.

提交回复
热议问题