vimuth vimuth - 7 months ago 48
Javascript Question

Echo json encoded string in symfony twig

I trying to echo json encode string in twig. This is my code,

Controller

$jsonArray = array(
array(
'label' => 'CN Clogs Beach',
'data' => 5
),
array(
'label' => 'Prod my prod',
'data' => 5
),
array(
'label' => 'New Pro',
'data' => 3
)
);

$jsonArray = json_encode($jsonArray);

return $this->render("EagleAdminBundle:dashboard:index.html.twig", array(
'jsonArray' => $jsonArray
));


This is twig file

<script type="text/javascript">
var data = {{ jsonArray }};
</script>


Instead of getting json array I get something like this,

var data = [{&quot;label&quot;:&quot;CN Clogs Beach&quot;,&quot;data&quot;:5},{&quot;label&quot;:&quot;Prod my prod&quot;,&quot;data&quot;:5},{&quot;label&quot;:&quot;New Pro&quot;,&quot;data&quot;:3}];

Answer

Try

<script type="text/javascript">
var data = {{ jsonArray | raw }};
</script>

or

var data = $.parseJSON('{{ jsonArray | raw }}');