k0pernikus k0pernikus - 7 months ago 86
PHP Question

How to escape entire block with html-entities via twig?

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:

&lt;ThisShouldBeEscaped&gt;
&lt;ButItIsnt&gt;Dang&lt;/ButItIsnt&gt;
&lt;/ThisShouldBeEscaped&gt;


yet I get a complete raw XML response:

<rawXml>
<message>
<ThisShouldBeEscaped>
<ButItIsnt>Dang</ButItIsnt>
</ThisShouldBeEscaped>
</message>
</rawXml>


What am I doing wrong?

Answer

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>
Comments