Hamza Hamza - 14 days ago 9
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?


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


return $this->render(
         'myArray' => array('foo', 'bar', 'z')

Twig view

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