Twig 中文文档
  • 关于
  • Twig 1.x
  • Twig 2.x
    • 介绍
    • 安装
    • Twig for 模板设计师
    • Twig for 开发者
    • 扩展 Twig
    • Twig 内部机制
    • 弃用功能
    • Twig 方法
    • 编码标准
    • API
    • 附录*核心扩展
      • 标签(Tags)
        • 自动转义 autoescape
        • 块 block
        • do
        • embed
        • extends
        • filter
        • flush
        • for
        • from
        • if
        • import
        • include
        • macro
        • sandbox
        • set
        • spaceless
        • use
        • verbatim
        • with
      • 过滤器(Filters)
        • abs
        • batch
        • capitalize
        • convert_encoding
        • date
        • date_modify
        • default
        • escape
        • first
        • format
        • join
        • json_encode
        • keys
        • last
        • length
        • lower
        • merge
        • nl2br
        • number_format
        • raw
        • replace
        • reverse
        • round
        • slice
        • sort
        • split
        • striptags
        • title
        • trim
        • upper
        • url_encode
      • 函数(Functions)
        • attribute
        • block
        • constant
        • cycle
        • date
        • dump
        • include
        • max
        • min
        • parent
        • random
        • range
        • source
        • template_from_string
      • 测试(Tests)
        • constant
        • defined
        • divisible by
        • empty
        • even
        • iterable
        • null
        • odd
        • same as
      • Operators(操作符)
  • 附录*资料整理
Powered by GitBook
On this page

Was this helpful?

  1. Twig 2.x
  2. 附录*核心扩展
  3. 标签(Tags)

自动转义 autoescape

Previous标签(Tags)Next块 block

Last updated 5 years ago

Was this helpful?

原文: 翻译:小虾米(QQ:509129)

自动转义(autoescape)

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

{% 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 %}
{% autoescape %}
    {{ safe_value|raw }}
{% endautoescape %}

Twig足够智能,无法通过转义过滤器转义已转义的值。

Twig无法转义静态表达式:

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

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

当自动转义启用时,除了显式标记为安全的值外,所有东西都是默认的。这些可以通过使用过滤器在模板中标记:

函数返回模板数据(如宏和父类)总是返回安全标记。

对于章节,提供了更多关于何时以及如何使用自动转义的信息。

autoescape
raw
macros
parent
Twig for 开发者