Use Javascript to access a variable passed through Twig

clifford.duke picture clifford.duke · Dec 18, 2012 · Viewed 61.5k times · Source

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.

Answer

Supericy picture Supericy · Dec 18, 2012

You might have to json_encode the array, try this:

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