Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Javascript to access a variable passed through Twig

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.

like image 852
clifford.duke Avatar asked Dec 18 '12 08:12

clifford.duke


People also ask

Can you use Twig in JavaScript?

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.

How do you use variables in Twig?

In Twig templates variables can be accessed using double curly braces notation {{ variableName }} .

Can PHP access JavaScript variable?

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.


2 Answers

You might have to json_encode the array, try this:

<script>     $(document).ready(function(){         var test = {{ testArray|json_encode|raw }};     }); </script> 
like image 133
Supericy Avatar answered Oct 13 '22 00:10

Supericy


First, send the data json encoded from controller and

then in javascript,

var context= JSON.parse('{{ YourArrayFromController|raw}}'); 
like image 24
user3189566 Avatar answered Oct 13 '22 01:10

user3189566