# 自动转义 autoescape

> 原文：[autoescape](https://twig.sensiolabs.org/doc/2.x/tags/autoescape.html)\
> 翻译：小虾米（QQ:509129）

## 自动转义（autoescape）

无论是否启用了自动转义，您都可以通过使用自动转义标记来标记一个模板的一个片段:

```markup
{% 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](https://twig.sensiolabs.org/doc/2.x/filters/raw.html)过滤器在模板中标记:

```markup
{% autoescape %}
    {{ safe_value|raw }}
{% endautoescape %}
```

函数返回模板数据(如宏[macros](https://twig.sensiolabs.org/doc/2.x/tags/macro.html)和父类[parent](https://twig.sensiolabs.org/doc/2.x/functions/parent.html))总是返回安全标记。

> Twig足够智能，无法通过转义过滤器转义已转义的值。
>
> Twig无法转义静态表达式:
>
> ```markup
> {% set hello = "<strong>Hello</strong>" %}
> {{ hello }}
> {{ "<strong>world</strong>" }}
> ```
>
> 将被渲染为"\<strong>Hello\</strong> **world**"。

对于章节[Twig for 开发者](https://twig.sensiolabs.org/doc/2.x/api.html)，提供了更多关于何时以及如何使用自动转义的信息。
