Use Javascript to access a variable passed through Twig

前端 未结 4 1663
南旧
南旧 2020-11-28 09:24

I have a controller that passes an array to a twig template, which I want to use in a script written on that page. How would I go about doing that?

I\'ve tried this

相关标签:
4条回答
  • 2020-11-28 10:09

    In My Controller I Install SerializerBundle

    $serializer = $this->get('serializer');
            $countries = $this->getDoctrine()->getRepository("QSCORBundle:CountryMaps")->findAll();
            $jsonCountries = $serializer->serialize($countries, 'json');
     return $this->render('QSCORBundle:Default:index.html.twig',array("countries"=> $jsonCountries));
    

    And In My File Twig

    <script type="text/javascript" >
     var obj = {{ countries|json_encode|raw }};
     var myObject = eval('(' + obj + ')');
    
     console.log(myObject[0]['capital_latitude'] + " " + myObject[0]['capital_longitude']);//for the First Element
    </script>
    
    0 讨论(0)
  • 2020-11-28 10:14

    I do it this way:

    Return of the controller test.data then

    $test = array('data' => array('one','two'))
    

    Twig:

    <div id="test" data-is-test="{{ test.data|json_encode }}"></div>
    

    Js:

    $(document).ready(function() {
        var test = $('#test').data("isTest");
        console.log(test);
    });
    

    Output:

     ["one", "two"]
    

    documentation here

    0 讨论(0)
  • 2020-11-28 10:20

    You might have to json_encode the array, try this:

    <script>
        $(document).ready(function(){
            var test = {{ testArray|json_encode|raw }};
        });
    </script>
    
    0 讨论(0)
  • 2020-11-28 10:29

    First, send the data json encoded from controller and

    then in javascript,

    var context= JSON.parse('{{ YourArrayFromController|raw}}');
    
    0 讨论(0)
提交回复
热议问题