drupal-twig について
Drupal のテーマ開発者向けに、Twig テンプレートの実践方法をまとめたスキルです。翻訳、ライブラリのアタッチ、安全なマークアップ、デバッグ、コンポーネントの利用を扱います。
主な機能
- 01Twig の自動エスケープ指針
- 02`{% trans %}` による文字列翻訳
- 03CSS・JS ライブラリのアタッチ
- 04安全なコンテンツとフィールド描画
- 05`dump()` によるデバッグ
- 06Drupal SDC コンポーネント例
活用シーン
- 01Twig テンプレートの出力安全性確認
- 02テンプレートへの翻訳可能な文字列追加
- 03マークアップへのテーマライブラリ追加
- 04フィールドや SDC コンポーネントの描画
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ edutrul/ drupal-ai --skill drupal-twigインストール後、Claude Code で/drupal-twigを入力して読み込まれたか確認します。
同梱ファイルREADME.md
詳細
Drupal Twig のベストプラクティス
基本ルール
- 変数は自動的にエスケープされます。出所がわかっている場合を除き、
|escapeは使用しないでください - ユーザーに表示する文字列にはすべて
{% trans %}を使用してください - CSS/JS には
{{ attach_library() }}を使用し、インライン記述は避けてください - Twig 内でサービスにアクセスしたり、クエリを実行したりしないでください
翻訳
{# Simple string #}
{% trans %}Hello world{% endtrans %}
{# With variable #}
{% trans %}Hello {{ name }}{% endtrans %}
{# Plural #}
{% trans %}
@count item
{% plural count %}
@count items
{% endtrans %}
ライブラリの読み込み
{{ attach_library('my_module/my-library') }}
{{ attach_library('mytheme/component-name') }}
安全なマークアップ
{# Already sanitized by Drupal — safe to use |raw #}
{{ content.body }}
{{ content|raw }}
{# Render a single field #}
{{ content.field_image }}
{# Render with a specific view mode #}
{{ node|view('teaser') }}
デバッグ
{# Dump variables (requires Twig debug enabled) #}
{{ dump(content) }}
{{ dump(node) }}
{{ dump(_context|keys) }}
よく使う変数
{# Node template #}
{{ node.title.value }}
{{ node.bundle() }}
{{ node.id() }}
{{ node.isPublished() }}
{# Check if field is set #}
{% if content.field_image|render %}
{{ content.field_image }}
{% endif %}
{# Field items loop #}
{% for item in node.field_tags %}
{{ item.entity.name.value }}
{% endfor %}
SDC コンポーネント(Drupal 10.3+)
{# Use a component #}
{% include 'mytheme:button' with {
label: 'Click me',
url: path('entity.node.canonical', {node: node.id()}),
variant: 'primary',
} %}
テンプレート候補のフック
#[Hook('theme_suggestions_node_alter')]
public function themeSuggestionsNodeAlter(array &$suggestions, array $variables): void {
$node = $variables['elements']['#node'];
$view_mode = $variables['elements']['#view_mode'];
$suggestions[] = 'node__' . $node->bundle() . '__' . $view_mode;
}
コメント
Markdown 対応