简体   繁体   中英

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?

我认为您应该使用原始过滤器,例如:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM