Twig

灵活、快速且安全的
PHP 模板引擎

a Symfony Product
Docs Tags autoescape
您正在阅读 Twig 3.x 的文档。切换到 Twig 的文档 1.x, 2.x

问题与反馈

许可

Twig 文档 根据新的 BSD 许可 获得许可。

autoescape

无论是否启用自动转义,您都可以使用 autoescape 标签标记模板的某个部分是否需要转义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{% autoescape %}
    Everything will be automatically escaped in this block
    using the HTML strategy
{% endautoescape %}

{% autoescape 'html' %}
    Everything will be automatically escaped in this block
    using the HTML strategy
{% endautoescape %}

{% autoescape 'js' %}
    Everything will be automatically escaped in this block
    using the js escaping strategy
{% endautoescape %}

{% autoescape false %}
    Everything will be outputted as is in this block
{% endautoescape %}

当启用自动转义时,默认情况下会转义所有内容,除非显式标记为安全的值。这些值可以在模板中使用 raw 过滤器进行标记

1
2
3
{% autoescape %}
    {{ safe_value|raw }}
{% endautoescape %}

返回模板数据的函数(如 macrosparent)始终返回安全标记。

注意

当自动转义策略与 escape 过滤器应用的策略相同时,Twig 足够智能,不会转义已经被 escape 过滤器转义的值。

注意

Twig 不会转义静态表达式

1
2
3
{% set hello = "<strong>Hello</strong>" %}
{{ hello }}
{{ "<strong>world</strong>" }}

将渲染为 "<strong>Hello</strong> world"。

注意

章节 Twig for Developers 提供了关于何时以及如何应用自动转义的更多信息。