
はじめに
Twigには、テンプレート内で直接使用できる便利な関数が、たくさんあります。Drupal 9 のコアには、Drupal特有のカスタム関数がいくつか追加されています。この関数は、TwigExtensionクラスで定義されています。独自のカスタムTwig関数をカスタムモジュールで定義することもできます。
Twig 関数リスト(List of Twig Functions)
Drupal コアには、Drupal 特有のカスタム関数がいくつか追加されています。この関数は、TwigExtension クラスで定義されています。
独自のカスタム Twig 関数をカスタムモジュールで定義することもできます(しかしテーマには含まれません)。カスタム 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 オブジェクトと同様に使用可能です。
8.3.x で導入されました |
---|
変更履歴: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, $url, $attributes)
このヘルパー関数は、最初のパラメータでテキストを受け取り、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>
特定のノードへの絶対 URL を生成:
<a href="{{ url('entity.node.canonical', { 'node': 123 }) }}">{{ 'Visit node 123'|t }}</a>
ノードテンプレート内で node 変数が存在する場合、現在のノードに対する絶対 URL を生成することができます:
<a href="{{ url('entity.node.canonical', { 'node': node.id() }) }}">{{ 'Visit this page'|t }}</a>