Hamza Hamza - 1 year ago 130
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:


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

Twig view

{% block javascripts %}
    <script type="text/javascript">
        var myArray = '{{ myArray | json_encode | raw }}';
{% endblock %}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download