scruffycoder86
scruffycoder86

Reputation: 549

JSON String passed incorrectly in Twig Template

I have two arrays from my controller that I pass to my twig template. This twig template then passes these values onto my javascript file but how they end up there is incorrect.

//Controller

return $app['twig']->render({template_name}, array(
    'cities' => $this->cities,
   ));

In my twig template I have the code snippet below:

var cities = "{{ cities|json_encode(constant('JSON_PRETTY_PRINT')) }}";

I have followed the suggestion made by Sensio's Lab Documentation and this doesn't seem to work for me.

I end up with a json string as shown below:

{"B01":["Gaborone"]...}

Also JSON_PRETTY_PRINT is said to be not defined. If I remove this constant then the error is gone. The most important thing for me is to have the correct json format and I have tried all the suggestions I came through on the net.

Any suggestions on how I can get my json to be outputted correctly?

Upvotes: 0

Views: 537

Answers (1)

Gabor Szabo
Gabor Szabo

Reputation: 21

I think you should use the raw filter, like:

var cities = "{{ cities|json_encode(constant('JSON_PRETTY_PRINT'))|raw }}";

Upvotes: 1

Related Questions