Escaping html in twig

I am using the import plugin to import the contents of json files into pages.

In order for the json to render fully I am having to escape, as per the twig docs at https://twig.symfony.com/doc/2.x/filters/escape.html

{{ page.header.imports.ex_config|json_encode(constant(‘JSON_PRETTY_PRINT’)) | escape }}

This is giving me a problem in that the urls, html and xml which is included in the json is now being rendered with unwanted escape characters, for example a url is being rendered with unwanted backslashes:

“serverPublicAddress”: “http:\/\/127.0.0.1:8000”,

Is there any way around this? Is it possible to customize the escape strategy to prevent it happening?

try this:

{{ page.header.imports.ex_config|json_encode(constant('JSON_PRETTY_PRINT') b-or constant('JSON_UNESCAPED_SLASHES'))|raw }}
1 Like

Yes @paul that has worked. Thank you :slight_smile:

Hello again @paul

I have just tested this further and it is giving me a problem with some json parameters which contain xml. This xml content has escaped backslashes which must be retained…

Can you think of a fix for this?

you might have to manipulate it before encoding it with something like: http://php.net/manual/fr/function.simplexml-load-file.php

1 Like

Hi @paul

I got this working by using

{{ page.header.imports.ex_config|json_encode(constant('JSON_PRETTY_PRINT') b-or constant('JSON_UNESCAPED_SLASHES'))|e('html') }}

I am now trying to achieve same thing with importing yaml files

I am using:

{{ page.header.imports.file1|yaml_emit(constant('YAML_ANY_ENCODING')) }}

but the xml metadata field which, in the original file, is this:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><EntityDescriptor entityID="your_subdomain.com" xmlns="urn:oasis:names:tc:SAML:2.0:metadata"><SPSSODescriptor AuthnRequestsSigned="false" WantAssertionsSigned="true" protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol"><NameIDFormat>urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress</NameIDFormat><AssertionConsumerService index="1" Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location="https://accountname.com/access/saml"/></SPSSODescriptor></EntityDescriptor>

Is coming out as:

metadata: urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress

I am using the documentation at http://php.net/manual/en/function.yaml-emit.php

Would you know how to control the escaping for the yaml file?

I’ve actually mostly answered my own question for this here:

Still having an issue with a >- block chomping indicator being removed