Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig json_encode with multiple options

Tags:

php

twig

symfony

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"
}
like image 562
caramba Avatar asked Apr 29 '16 11:04

caramba


1 Answers

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')) }}
like image 98
Syjin Avatar answered Oct 09 '22 08:10

Syjin