滚动
函数 —— 在 Twig 模板中
Twig 提供了一系列便捷函数,可以直接在模板中使用。
Drupal 内核添加了一些特定于 Drupal 的自定义函数。它们定义在 TwigExtension 类 中。
你也可以在自定义模块(而不是主题)中定义自己的 Twig 函数。示例可参考 core/modules/system/tests/modules/twig_extension_test/src/TwigExtension/TestExtension.php。
attach_library($library)
将一个资源库附加到模板。
{{ attach_library('classy/node') }}
create_attribute($attributes)
在 Twig 模板中使用 create_attribute() 函数创建新的 Attribute 对象。它们可以像模板中传入的 Attribute 对象一样操作。
参考变更说明:https://www.drupal.org/node/2818293
{% set my_attribute = create_attribute() %}
{%
set my_classes = [
'kittens',
'llamas',
'puppies',
]
%}
<div{{ my_attribute.addClass(my_classes).addAttribute('id', 'myUniqueId') }}>
{{ content }}
</div>
<div{{ create_attribute({'class': ['region', 'region--header']}) }}>
{{ content }}
</div>
file_url($uri)
这个辅助函数接受文件的 URI 并生成文件的相对 URL 路径。
{{ file_url(node.field_example_image.entity.uri.value) }}
link($text, $uri, $attributes)
这个辅助函数的第一个参数是 text,第二个参数是 uri。
示例:
{{ link(item.title, item.uri, { 'class':['foo', 'bar', 'baz']} ) }}
path($name, $parameters, $options)
根据路由名称和参数创建 [相对] URL 路径。
{# 链接到 frontpage 视图。#}
<a href="{{ path('view.frontpage.page_1') }}">{{ 'View all content'|t }}</a>
{# 链接到用户实体/个人主页。#}
<a href="{{ path('entity.user.canonical', {'user': user.id}) }}">{{ 'View user profile'|t }}</a>
{# 链接到节点页面。#}
<a href="{{ path('entity.node.canonical', {'node': node.id}) }}">{{ 'View node page'|t }}</a>
url 和 path 函数的定义位置与 \Symfony\Bridge\Twig\Extension\RoutingExtension 中的类似。
url($name, $parameters, $options)
根据路由名称和参数创建绝对 URL:
<a href="{{ url('view.frontpage.page_1') }}">{{ 'View all content'|t }}</a>
为当前 URL 创建绝对链接:
<a href="{{ url('<current>') }}">{{ 'Reload'|t }}</a>
为首页创建绝对链接:
<a href="{{ url('<front>') }}">{{ 'Home'|t }}</a>