在模板中使用属性
许多 Twig 模板会有一个或多个 Attribute 对象作为变量传入。Attribute 对象的任务是存储一组 HTML 属性,同时为开发者提供有用的方法与这些数据交互,并且可以轻松打印属性。例如,attribute.addClass('myclass') 可以方便地添加一个类,而不必担心字符串拼接的细节。
在模板中,属性通常应如下所示:
<div{{ attributes }}></div>
在标签名和 Twig 语法之间不应有空格。Drupal 8 核心附带的 "stable" 主题中有许多属性的示例可供学习。
默认情况下,以下 Attribute 对象变量在所有模板中都可用:attribute、title_attributes 和 content_attributes。
你可以使用调试工具(kint()、dump()、dpm() 等)来检查可用的内容。下面是 node.html.twig 文件中使用 {{kint(attribute)}} 的示例。

属性方法
以下是一些可用于 Attribute 对象的有用方法:
attributes.addClass()
添加类或将其合并到现有的 CSS 类数组中。
单个类:
<div{{ attributes.addClass('my-class') }}></div>
多个类:
{%
set classes = [
'red',
'green',
]
%}
<div{{ attributes.addClass(classes) }}></div>
输出为 <div class="red green"></div>。
attributes.removeClass()
从 Attribute 对象中移除类。用法与 addClass 类似。假设你从其他地方(例如预处理函数)获取了类变量。
{% set classes = [ 'red', 'green', 'blue' ] %}
<div{{ attributes.addClass(classes).removeClass('green') }}></div>
输出为 <div class="red blue"></div>。
attribute.setAttribute($attribute, $value)
为属性键设置值。
<div{{ attributes.setAttribute('id', 'myID') }}></div>
输出为 <div id="myID"></div>
attributes.removeAttribute($attribute)
从 Attribute 对象中移除属性。
<div{{ attributes.removeAttribute('id') }}></div>
attributes.hasClass($class)
检查类数组中是否包含指定的 CSS 类。
{% if attributes.hasClass('myClass') %}
{# do stuff #}
{% endif %}
在 Twig 中创建属性
从 Drupal 8.3.x 开始,新增了 Twig 函数 create_attribute()。参见变更记录:https://www.drupal.org/node/2818293.
这将提供一个新的空 Attribute 对象,用于创建属性。
{% set my_attribute = create_attribute() %}
{%
set my_classes = [
'kittens',
'llamas',
'puppies',
]
%}
<div{{ my_attribute.addClass(my_classes).setAttribute('id', 'myUniqueId') }}>
{{ content }}
</div>
<div{{ create_attribute({'class': ['region', 'region--header']}) }}>
{{ content }}
</div>
其他有用的片段
点式调用可以链式使用
{% set classes = ['red', 'green', 'blue'] %}
{% set my_id = 'specific-id' %}
{% set image_src = 'https://www.drupal.org/files/powered-blue-135x42.png' %}
<img{{ attributes.addClass(classes).removeClass('green').setAttribute('id', my_id).setAttribute('src', image_src) }}>
输出为 <img id="specific-id" class="red blue" src="https://www.drupal.org/files/powered-blue-135x42.png">
使用 without 过滤器
twig 过滤器 without 可移除部分属性:
<div class="myclass {{ attributes.class }}"{{ attributes|without('class') }}></div>
注意:大多数情况下应避免像上面这样使用代码,而应优先使用 addClass()。
在 Twig 模板中手动指定属性时要格外小心。务必始终将属性值用双引号括起来,否则网站可能会暴露于 XSS 攻击。Twig 会自动对双引号内容进行转义,从而防止 XSS 攻击。
以下 Twig 模板:
<b class={{ attributes.class }}>Hello<b>
如果用户输入为:
foo onclick=alert(bar)
输出结果将是:
<b class=foo onclick=alert(bar)>Hello</b>
这是带双引号的 Twig 模板:
<b class="{{ attributes.class }}">Hello<b>
相同输入的输出结果为:
<b class="foo " onclick="alert(bar)">Hello</b>
修改 without 属性
{% set attributes = attributes.addClass('my-class') %}
<div{{ attributes }}></div>