Twig 中的全局原始转义

Global raw escaping in Twig

是否可以设置一个指令,使特定范围内的 Twig 模板中的每个变量都将使用 raw filter 进行转义?

例如。

{% setAllRaw %}

    {{foo}} // this will be rendered as if foo|raw
    {{bar}} // this will be rendered as if bar|raw
    {{baz}} // this will be rendered as if baz|raw

{% endSetAllRaw %}

而不是必须明确地写

    {{foo|raw}} 
    {{bar|raw}}
    {{baz|raw}}

要是能被子模板继承就好了..

{% setAllRaw %}

    {{foo}} // this will be rendered as if foo|raw
    {% include 'component.twig' %} // every variable in this template will also be rendered as raw

{% endSetAllRaw %}

** AND/OR **

有没有办法在控制器中指示将变量呈现为原始变量

例如。

// Controller

$data['foo'] = renderAsRaw($foo);

return new Response($this->renderView('template.html.twig', $data));

// Template

{{foo}} // will be rendered as raw

我试过使用 autoescape 但这并不像我上面描述的那样有效

{% autoescape %}
    {{foo}} // this does NOT render as raw
{% endautoescape %}

默认情况下,您的所有模板都使用自动转义。

您可以通过在 autoescape 块声明中添加 false 来禁用部分模板的 autoescape

{% autoescape false %}
    {{ rawVar }}
{% endautoescape %}

如果您需要在所有模板中禁用自动转义,您可以在 config.yml:

中设置全局参数
twig:
    autoescape: false