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?

4
  • 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 Commented Apr 12, 2017 at 15:03
  • how can i do this? Commented Apr 12, 2017 at 15:11
  • We don't know what you want to do, add a better example Commented Apr 12, 2017 at 15:13
  • Possible duplicate of Use Javascript to access a variable passed through Twig Commented Apr 12, 2017 at 16:19

2 Answers 2

5

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 %}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you that's working, just in case somebody needs this, to parse the array myArray you can use : var jsonData = JSON.parse(myArray);
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

2 Comments

In my case, i'm sending php array to javascript , but i don't know how to parse it.
You could use the Symfony serializer or if its some simple object: Use Javascript to access a variable passed through Twig

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.