Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 366
k0pernikus Avatar asked Oct 20 '25 06:10

k0pernikus


1 Answers

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>
like image 153
slax0r Avatar answered Oct 22 '25 19:10

slax0r



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!