[Drupal]Twigの小ネタ集


※随時追加予定

ユーザーの権限をチェックする

   {% if user.hasPermission('administer nodes') %}
      ... do something
    {% endif %}

ユーザーの役割をチェックする

{% if 'ROLENAME' in user.getroles(TRUE)  %}
  <p>The user has the role "ABC".</p>
{% endif %}

ルートから相対パスを取得

{{ path('entity.user.canonical', {'user': user.id}) }}

ルートからURLを取得


{{ url('view.frontpage.page_1') }}

エンティティをそのままレンダリングする

{{ node }}

特定のフィールドをレンダリングする

{{ node.body }}

特定のフィールドをフォーマッターを通してレンダリングする

あらかじめ表示設定でフォーマッターを指定しておく

{{ node.body|view }}

日付を特定のフォーマットを通してレンダリングする

/admin/config/regional/date-timeにあるフォーマットが使える

{{ node.created.value|format_date('long') }}

特定のフィールドの値をHTMLタグが入ったプレーンテキストの状態で表示する

{{ node.body.value }}

特定のフィールドのHTMLタグ無しの値を表示する

{{ content.body.0 }}

複数フィールドの値をレンダリングする

{% for delta, tag in node.tags[0] %}
  {{ delta }} => {{ tag }}
{% endfor %}

フィールドのラベルを表示する

{{ node[field_name].fieldDefinition.label }}

フィールドで参照されているエンティティのフィールドを表示する

# ノードのfield_editorで参照されているユーザーのfield_summaryをレンダリングする
{{ node.field_editor.entity.field_summary }}

リンクのタイトルを表示する

{{ node.field_link.0.url }}

ファイルのURIを表示する


<img src="{{ file_url(node.field_image.entity.uri.value) }}" alt="{{ node.field_image.alt }}">

ファイルのURLを表示する


{{ file_url(node.field_example_image.entity.uri.value) }}

リストの選択肢のラベルを取得する


{{ node.filter_list.getSetting('allowed_values')[list_value] }}