I want to create an xml output that contains html encoded block.
This is my twig snipplet:
<rawXml>
<message>
{% autoescape 'html' %}
<ThisShouldBeEscaped>
<ButItIsnt>Dang</ButItIsnt>
</ThisShouldBeEscaped>
{% endautoescape %}
</message>
</rawXml>
On rendering, I expected to message content to be html-encoded this way:
<ThisShouldBeEscaped>
<ButItIsnt>Dang</ButItIsnt>
</ThisShouldBeEscaped>
yet I get a complete raw XML response:
<rawXml>
<message>
<ThisShouldBeEscaped>
<ButItIsnt>Dang</ButItIsnt>
</ThisShouldBeEscaped>
</message>
</rawXml>
What am I doing wrong?
Twig does not by default escape template markup. If you wish to escape your HTML in this way, then set it to a variable first and then either autoescape
it, or use a regular escape
:
<rawXml>
<message>
{% set myHtml %}
<ThisShouldBeEscaped>
<ButItIsnt>Dang</ButItIsnt>
</ThisShouldBeEscaped>
{% endset %}
{% autoescape 'html' %}
{{ myHtml }}
{% endautoescape %}
<!-- or -->
{{ myHtml|escape }}
</message>
</rawXml>