如何使用 json_encode twig 函数在 twig 文件中使用 php json_encode 选项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12258225/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:09:58  来源:igfitidea点击:

How to use php json_encode options in twig file with json_encode twig function

phpsymfonytwig

提问by aditya

I am trying to use twig json_encode function but when I do this

我正在尝试使用 twig json_encode 函数,但是当我这样做时

    var packageDetails =  {{(packageDetails|json_encode)}};

and packageDetails is an array of array passed from controller

和 packageDetails 是从控制器传递的数组数组

It gives me error saying

它给了我错误说

    invalid property id 

because of "so I want to use escape filter; how do I use it?

因为"所以我想使用转义过滤器;我该如何使用它?

回答by Mike

Is it simply because you are not wrapping your output in quotes?

仅仅是因为您没有将输出括在引号中吗?

var variable = '{{{reference}}}';

Update:

更新:

The actual answer to solve the question was adding |raw to the tag as per comments

解决问题的实际答案是根据评论将 |raw 添加到标签中

var packageDetails =  {{(packageDetails|json_encode|raw)}};

回答by Tac Tacelosky

You can add the options in the following way:

您可以通过以下方式添加选项:

{{ data|json_encode(constant('JSON_PRETTY_PRINT'))|raw }}

Adding this because it answers the question in your title, but it sounds like the raw filter was really what you were looking for. Still, others may find this useful.

添加这个是因为它回答了你标题中的问题,但听起来原始过滤器确实是你想要的。尽管如此,其他人可能会发现这很有用。

回答by everyman

For anyone, who has similar problem with Blade / Laravel5.x

对于任何与 Blade / Laravel5.x 有类似问题的人

var v = JSON.parse('{!! $v !!}');