Scroll
関数 - 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オブジェクトを作成します。これらのオブジェクトは、Twigテンプレートに入る他の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、2番目のパラメーターとしてuriを受け取ります
例:
{{ link(item.title, item.uri, { 'class':['foo', 'bar', 'baz']} ) }}
path($name, $parameters, $options)
ルートの名前とパラメーターを指定して[相対]URLパスを作成します。
{# Link to frontpage view. #}
<a href="{{ path('view.frontpage.page_1') }}">{{ 'View all content'|t }}</a>
{# Link to user entity/profile page. #}
<a href="{{ path('entity.user.canonical', {'user': user.id}) }}">{{ 'View user profile'|t }}</a>
{# Link to node page. #}
<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の絶対URLを作成します:
<a href="{{ url('<current>') }}">{{ 'Reload'|t }}</a>
フロントページの絶対URLを作成します:
<a href="{{ url('<front>') }}">{{ 'Home'|t }}</a>