简体   繁体   English

JSON字符串在Twig模板中传递错误

[英]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. 然后,该树枝模板将这些值传递到我的javascript文件中,但是它们最终如何出现是不正确的。

//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. 我遵循了Sensio的实验室文档的建议,这似乎对我不起作用。

I end up with a json string as shown below: 我最终得到一个json字符串,如下所示:

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

Also JSON_PRETTY_PRINT is said to be not defined. 另外,JSON_PRETTY_PRINT也未定义。 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. 对我来说,最重要的是拥有正确的json格式,我已经尝试了所有在网上提出的建议。

Any suggestions on how I can get my json to be outputted correctly? 关于如何使我的json正确输出的任何建议?

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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