关于 drupal-twig
面向 Drupal 主题开发者的 Twig 模板实践指南,涵盖翻译、库附加、安全标记、调试和组件使用。
主要功能
- 01Twig 自动转义指引
- 02使用 `{% trans %}` 翻译字符串
- 03附加 CSS 和 JS 库
- 04安全内容与字段渲染
- 05使用 `dump()` 调试
- 06Drupal SDC 组件示例
适用场景
- 01检查 Twig 模板输出安全性
- 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 %} - 使用
{{ attach_library() }}引入 CSS/JS — 切勿内联 - 切勿在 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