Use the json pretty print with the Twig json_encode filter

Published on 2019-08-17 • Modified on 2019-08-17

This is another example where the constant Twig function can be helpful. In this case we get the JSON_PRETTY_PRINT PHP constant to pass it to the json_encode filter. (as the second argument of course, the first is obviously the variable to display)


{hello: "world", foo: {bar: "doo", bar2: "doo2"}}|json_encode(constant('JSON_PRETTY_PRINT')) }}
Code execution output:
{
    "hello": "world",
    "foo": {
        "bar": "doo",
        "bar2": "doo2"
    }
}

 More on Stackoverflow   Read the doc  Random snippet