如何通过 twig 使用 html 实体转义整个块?

k0p*_*kus 4 php html-encode html-entities symfony twig

我想创建一个包含 html 编码块的 xml 输出。

这是我的树枝片段:

<rawXml>
    <message>
        {% autoescape 'html' %}
            <ThisShouldBeEscaped>
                <ButItIsnt>Dang</ButItIsnt>
            </ThisShouldBeEscaped>
        {% endautoescape %}
    </message>
</rawXml>
Run Code Online (Sandbox Code Playgroud)

在渲染时,我希望以这种方式对消息内容进行 html 编码:

&lt;ThisShouldBeEscaped&gt;
    &lt;ButItIsnt&gt;Dang&lt;/ButItIsnt&gt;
&lt;/ThisShouldBeEscaped&gt;
Run Code Online (Sandbox Code Playgroud)

但我得到了完整的原始 XML 响应:

<rawXml>
    <message>
        <ThisShouldBeEscaped>
            <ButItIsnt>Dang</ButItIsnt>
        </ThisShouldBeEscaped>
    </message>
</rawXml>
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

sla*_*x0r 5

默认情况下,Twig 不会转义模板标记。如果您希望以这种方式转义 HTML,请先将其设置为变量,然后再将autoescape其设置为变量,或者使用常规的escape

<rawXml>
    <message>
        {% set myHtml %}
        <ThisShouldBeEscaped>
            <ButItIsnt>Dang</ButItIsnt>
        </ThisShouldBeEscaped>
        {% endset %}
        {% autoescape 'html' %}
            {{ myHtml }}
        {% endautoescape %}
        <!-- or -->
        {{ myHtml|escape }}
    </message>
</rawXml>
Run Code Online (Sandbox Code Playgroud)