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:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.