How AJAX calls work with TWIG

前端 未结 2 2020
名媛妹妹
名媛妹妹 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 %}
    <p>My header,  not reloaded with ajax</p>
    {% endif %}
    
    <p>My content, reloaded with ajax</p>
    
    {% if request.ajax == false %}
    <p>Other content,  not reloaded with ajax</p>
    {% 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.

    0 讨论(0)
  • 2021-02-02 01:17

    Directly in the template:

    {% if app.request.isXmlHttpRequest() %}
      // code if ajax request
    {% else %}
      // code if not ajax request
    {% endif %}
    
    0 讨论(0)
提交回复
热议问题