Search code examples
phpjavascriptsymfonytwig

Use Javascript to access a variable passed through Twig


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.


Solution

  • 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>