Use Javascript to access a variable passed through Twig

PhpJavascriptSymfonyTwig

Php Problem Overview


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 in my .twig template:

<script>
    $(document).ready(function(){
        var test = {{ testArray }};
});
</script>

but that only works if it's a string.

Php Solutions


Solution 1 - Php

You might have to json_encode the array, try this:

<script>
    $(document).ready(function(){
        var test = {{ testArray|json_encode|raw }};
    });
</script>

Solution 2 - Php

First, send the data json encoded from controller and

then in javascript,

var context= JSON.parse('{{ YourArrayFromController|raw}}');

Solution 3 - Php

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

Solution 4 - Php

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>

Solution 5 - Php

json_encode works well, in combination with the raw filter.

<script>
    $(document).ready(function(){
        let test = {{ testArray | json_encode(constant('JSON_HEX_TAG')) | raw }};
    });
</script>

Don't forget the JSON_HEX_TAG flag.
Otherwise, you can get broken HTML. A string containing <!--<script> is a good way to test that.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionclifford.dukeView Question on Stackoverflow
Solution 1 - PhpSupericyView Answer on Stackoverflow
Solution 2 - Phpuser3189566View Answer on Stackoverflow
Solution 3 - Phpshades3002View Answer on Stackoverflow
Solution 4 - PhpMourad MAMASSIView Answer on Stackoverflow
Solution 5 - PhpSébastienView Answer on Stackoverflow