1

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?

DarkBee
  • 16,592
  • 6
  • 46
  • 58
Hamza
  • 37
  • 1
  • 1
  • 8
  • 2
    You can't do that. The javascript variable `i` is only available at runtime. What you need to do is parse your `twig array` to a javascript one. [Related](http://stackoverflow.com/questions/13928729/use-javascript-to-access-a-variable-passed-through-twig) – DarkBee Apr 12 '17 at 15:03
  • how can i do this? – Hamza Apr 12 '17 at 15:11
  • We don't know what you want to do, add a better example – goto Apr 12 '17 at 15:13
  • Possible duplicate of [Use Javascript to access a variable passed through Twig](http://stackoverflow.com/questions/13928729/use-javascript-to-access-a-variable-passed-through-twig) – goto Apr 12 '17 at 16:19

2 Answers2

4

Twig is PHP. You send its values to javascript but you can't take javascript variables to php. (except AJAX etc... but not relevant here)

Possible:

/* javascript variable */
var name = {{ object.name }}
console.log(name);

Impossible:

/* javascript variable */
var name = 'toto';
{# Twig #}
{{ name }} // <- IMPOSSIBLE
goto
  • 7,908
  • 10
  • 48
  • 58
  • In my case, i'm sending php array to javascript , but i don't know how to parse it. – Hamza Apr 12 '17 at 15:15
  • You could use the Symfony serializer or if its some simple object: [Use Javascript to access a variable passed through Twig](http://stackoverflow.com/questions/13928729/use-javascript-to-access-a-variable-passed-through-twig) – goto Apr 12 '17 at 16:20
4

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 %}
Dany Badr
  • 81
  • 6
  • Thank you that's working, just in case somebody needs this, to parse the array myArray you can use : var jsonData = JSON.parse(myArray); – Hamza Apr 13 '17 at 09:13