简体   繁体   English

Twig json_encode有多个选项

[英]Twig json_encode with multiple options

From the TWIG documentaion about json_encode() filter they say: 从关于json_encode()过滤器的TWIG文档中,他们说:

json_encode json_encode

The json_encode filter returns the JSON representation of a value: json_encode过滤器返回值的JSON表示:

 {{ data|json_encode() }} 

Internally, Twig uses the PHP json_encode function. 在内部,Twig使用PHP json_encode函数。

Arguments 参数

options: A bitmask of json_encode options options:json_encode选项的位掩码

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

What I'm trying to do is to add multiple of those options. 我想要做的是添加多个选项。

I want the JSON_PRETTY_PRINT and JSON_UNESCAPED_SLASHES 我想要JSON_PRETTY_PRINTJSON_UNESCAPED_SLASHES

I have tried 我试过了

{{ array|json_encode(constant('JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES')) }}
{{ array|json_encode(constant('JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES')) }}
{{ array|json_encode(constant('JSON_PRETTY_PRINT', 'JSON_UNESCAPED_SLASHES')) }}

But none of them work. 但它们都不起作用。 How can I combine two options for TWIGs json_encode() filter? 如何为TWIGs json_encode()过滤器组合两个选项?

TwigFiddle here TwigFiddle在这里

{% set array = {'xxx': "one", 'yyy': "two", 'path': "/hello/world" } %}

{% autoescape false %}
    {{ array|json_encode() }}
    {{ array|json_encode(constant('JSON_PRETTY_PRINT')) }}
    {{ array|json_encode(constant('JSON_UNESCAPED_SLASHES')) }}
{% endautoescape %}

Desired output should be 期望的输出应该是

{
    "xxx": "one",
    "yyy": "two",
    "path": "/hello/world"
}

It seems that you need b-or for a bitwise or operation ( docs ) in twig. 看来你需要b-or在twig中进行按位或操作( docs )。

So something like this should work: 所以像这样的东西应该工作:

{{ array|json_encode(constant('JSON_PRETTY_PRINT') b-or constant('JSON_UNESCAPED_SLASHES')) }}

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

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