caramba
caramba

Reputation: 22490

Twig json_encode with multiple options

From the TWIG documentaion about json_encode() filter they say:

json_encode

The json_encode filter returns the JSON representation of a value:

{{ data|json_encode() }}

Internally, Twig uses the PHP json_encode function.

Arguments

options: A bitmask of json_encode options

({{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

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?

TwigFiddle here

{% 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"
}

Upvotes: 8

Views: 3220

Answers (1)

Syjin
Syjin

Reputation: 2810

It seems that you need b-or for a bitwise or operation (docs) in twig.

So something like this should work:

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

Upvotes: 13

Related Questions