admin管理员组

文章数量:1344241

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?

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?

Share Improve this question edited Apr 12, 2017 at 15:01 DarkBee 15.5k8 gold badges72 silver badges117 bronze badges asked Apr 12, 2017 at 14:57 Hamza Hamza 371 gold badge2 silver badges8 bronze badges 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 – DarkBee Commented Apr 12, 2017 at 15:03
  • how can i do this? – Hamza Commented Apr 12, 2017 at 15:11
  • We don't know what you want to do, add a better example – goto Commented Apr 12, 2017 at 15:13
  • Possible duplicate of Use Javascript to access a variable passed through Twig – goto Commented Apr 12, 2017 at 16:19
Add a ment  | 

2 Answers 2

Reset to default 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 %}

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

本文标签: Accessing javascript variable inside symfony twigStack Overflow