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 )始终返回安全标记。

注解

Twig足够聪明,不会通过 escape 过滤器。

注解

Twig不会转义静态表达式:

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

将呈现“<strong>Hello</strong> 世界 “。

注解

本章 Twig for Developers 提供有关何时以及如何应用自动转义的详细信息。