Hamza Hamza - 6 months ago 41
Twig Question

Accessing javascript variable inside {{ }} symfony twig

I have an array arr sent from the controller to a twig template containing some JavaScript script , i want to use for loop to access rows of the array like this:

for (var i = 0; i < 3; i++) {
alert('{{ arr[i] }}');
}


But the variable i is unknown, i get this error :


Variable "i" does not exist.


Any suggestions?

Answer Source

This is how to get a php array from the controller to a javascript array through twig:

Controller

return $this->render(
    'AppBundle:index.html.twig',
     array(
         'myArray' => array('foo', 'bar', 'z')
     )
);

Twig view

{% block javascripts %}
    <script type="text/javascript">
        var myArray = '{{ myArray | json_encode | raw }}';
    </script>
{% endblock %}