Use Javascript to access a variable passed through Twig
69,109
Solution 1
You might have to json_encode
the array, try this:
<script>
$(document).ready(function(){
var test = {{ testArray|json_encode|raw }};
});
</script>
Solution 2
First, send the data json encoded from controller and
then in javascript,
var context= JSON.parse('{{ YourArrayFromController|raw}}');
Solution 3
I do it this way:
Return of the controller test.data then
$test = array('data' => array('one','two'))
Twig:
<div id="test" data-is-test="{{ test.data|json_encode }}"></div>
Js:
$(document).ready(function() {
var test = $('#test').data("isTest");
console.log(test);
});
Output:
["one", "two"]
Solution 4
In My Controller I Install SerializerBundle
$serializer = $this->get('serializer');
$countries = $this->getDoctrine()->getRepository("QSCORBundle:CountryMaps")->findAll();
$jsonCountries = $serializer->serialize($countries, 'json');
return $this->render('QSCORBundle:Default:index.html.twig',array("countries"=> $jsonCountries));
And In My File Twig
<script type="text/javascript" >
var obj = {{ countries|json_encode|raw }};
var myObject = eval('(' + obj + ')');
console.log(myObject[0]['capital_latitude'] + " " + myObject[0]['capital_longitude']);//for the First Element
</script>
Author by
clifford.duke
Updated on February 08, 2022Comments
-
clifford.duke over 2 years
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.
-
belens over 10 yearsAny suggestions how to do the same with a array of objects?
-
valerij vasilcenko over 9 yearsDon't forget to add quotes
var test = '{{ testArray|json_encode|raw }}';
-
Yep_It's_Me about 9 yearsNo, you don't want to quote it. That will make the variable a string containing a json value. Without the quotes it is parsed correctly as an array object.
-
Amaury Hanser almost 7 years@JoséGabrielGonzález How would you do it ?
-
some_groceries almost 7 yearsi had problems with this, the keys orders were reversed while using alongside with leaflet library
-
Klesun about 4 yearsUm, what if some of values in your JSON has single quote? Like in
{"message": "Can't process"}
-
Sébastien over 2 yearsYou should pass the
JSON_HEX_TAG
flag tojson_encode
:json_encode(constant('JSON_HEX_TAG'))
. Otherwise, you can get broken HTML (try"<!--<script>"
).