64

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.

clifford.duke
  • 3,980
  • 10
  • 38
  • 63
  • 1
    Adding the current output and expected output to your question can make finding a solution to your problem much easier. – Supericy Dec 18 '12 at 08:26

5 Answers5

198

You might have to json_encode the array, try this:

<script>
    $(document).ready(function(){
        var test = {{ testArray|json_encode(constant('JSON_HEX_TAG'))|raw }};
    });
</script>
Dharman
  • 30,962
  • 25
  • 85
  • 135
Supericy
  • 5,866
  • 1
  • 21
  • 25
  • 3
    Don't forget to add quotes `var test = '{{ testArray|json_encode|raw }}';` – valerij vasilcenko Dec 04 '14 at 13:24
  • 15
    No, you don't want to quote it. That will make the variable a string containing a json value. Without the quotes it is parsed correctly as an array object. – Yep_It's_Me Mar 05 '15 at 23:50
  • 1
    You should pass the `JSON_HEX_TAG` flag to `json_encode`: `json_encode(constant('JSON_HEX_TAG'))`. Otherwise, you can get broken HTML (try `" – Sébastien Feb 07 '22 at 11:39
8

First, send the data json encoded from controller and

then in javascript,

var context= JSON.parse('{{ YourArrayFromController|raw}}');
HRM
  • 2,097
  • 6
  • 23
  • 37
user3189566
  • 107
  • 1
  • 7
5

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

shades3002
  • 879
  • 9
  • 11
1

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.

Sébastien
  • 2,236
  • 2
  • 20
  • 28
0

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>
Mourad MAMASSI
  • 849
  • 1
  • 11
  • 14