I have a controller that passes an array to a twig template, which I want to use in a script written on that page. How would I go about doing that?
I've tried this in my .twig template:
<script> $(document).ready(function(){ var test = {{ testArray }}; }); </script>
but that only works if it's a string.
Twig and JS code is more tightly knit. You can easily transfer Twig variables into JS. Your code is more portable - you can easily reuse component by just copying a single file to other project.
In Twig templates variables can be accessed using double curly braces notation {{ variableName }} .
JavaScript is the client side and PHP is the server side script language. The way to pass a JavaScript variable to PHP is through a request. This type of URL is only visible if we use the GET action, the POST action hides the information in the URL.
You might have to json_encode
the array, try this:
<script> $(document).ready(function(){ var test = {{ testArray|json_encode|raw }}; }); </script>
First, send the data json encoded from controller and
then in javascript,
var context= JSON.parse('{{ YourArrayFromController|raw}}');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With