Twig 中的全局原始转义

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


前任。


{% 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 %}

** 和/或 **


有没有办法在控制器中指示变量将被渲染为原始变量


前任。


// 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 %}


慕森王
浏览 54回答 1
1回答

长风秋雁

默认情况下,所有模板都使用自动转义。您可以通过添加块声明来禁用部分autoescape模板:falseautoescape{% autoescape false %}    {{ rawVar }}{% endautoescape %}如果您需要在所有模板中禁用自动转义,您可以在 config.yml 中设置全局参数:twig:    autoescape: false
打开App,查看更多内容
随时随地看视频慕课网APP