drupal-frontend

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Drupal Front End Development

Drupal前端开发

Overview

概述

Enable expert-level Drupal front end development capabilities. Provide comprehensive guidance for theme development, Twig templating, preprocessing, responsive design, and asset management for Drupal 8, 9, 10, and 11+.
启用专业级的Drupal前端开发能力,为Drupal 8、9、10和11+版本的主题开发、Twig模板编写、预处理、响应式设计和资源管理提供全面指导。

When to Use This Skill

何时使用该技能

Invoke this skill when working with:
  • Theme development: Creating or customizing Drupal themes
  • Twig templates: Writing or modifying .twig template files
  • Preprocessing: Implementing preprocess functions for templates
  • Template suggestions: Adding custom template naming patterns
  • CSS/JS libraries: Managing theme assets and dependencies
  • Responsive design: Implementing breakpoints and mobile-first design
  • Rendering system: Understanding Drupal's rendering pipeline
  • Theme hooks: Implementing theme-related hooks and alterations
在处理以下场景时调用该技能:
  • 主题开发:创建或自定义Drupal主题
  • Twig模板:编写或修改 .twig 模板文件
  • 预处理:为模板实现预处理函数
  • 模板建议:添加自定义模板命名规则
  • CSS/JS库:管理主题资源和依赖
  • 响应式设计:实现断点规则和移动端优先设计
  • 渲染系统:理解Drupal的渲染流程
  • 主题钩子:实现主题相关的hook和变更逻辑

Core Capabilities

核心能力

1. Theme Development

1. 主题开发

Build complete, standards-compliant Drupal themes with proper structure:
Quick start workflow:
  1. Use theme template from
    assets/theme-template/
    as starting point
  2. Replace
    THEMENAME
    with your theme's machine name
  3. Replace
    THEMELABEL
    with human-readable name
  4. Customize templates, CSS, JS, and libraries
  5. Enable theme and configure via Appearance UI
Theme components:
  • .info.yml
    - Theme metadata and configuration
  • .libraries.yml
    - CSS/JS library definitions
  • .theme
    - Preprocess functions and theme logic
  • .breakpoints.yml
    - Responsive breakpoints
  • templates/
    - Twig template files
  • css/
    - Stylesheets
  • js/
    - JavaScript files
Reference documentation:
  • references/theming.md
    - Complete theming guide with examples
构建结构规范、符合标准的完整Drupal主题:
快速启动工作流:
  1. assets/theme-template/
    中的主题模板为起点
  2. THEMENAME
    替换为你的主题机器名
  3. THEMELABEL
    替换为人类可读的主题名称
  4. 自定义模板、CSS、JS和库配置
  5. 启用主题并通过外观UI进行配置
主题组成部分:
  • .info.yml
    - 主题元数据和配置
  • .libraries.yml
    - CSS/JS库定义
  • .theme
    - 预处理函数和主题逻辑
  • .breakpoints.yml
    - 响应式断点配置
  • templates/
    - Twig模板文件
  • css/
    - 样式表文件
  • js/
    - JavaScript文件
参考文档:
  • references/theming.md
    - 带示例的完整主题开发指南

2. Twig Template System

2. Twig模板系统

Master Twig syntax and Drupal-specific extensions:
Twig fundamentals:
  • {{ variable }}
    - Print variables
  • {% if/for/set %}
    - Control structures and logic
  • {# comment #}
    - Comments and documentation
  • {{ var|filter }}
    - Apply filters to variables
  • {% extends %}
    - Template inheritance
  • {% block %}
    - Define overridable sections
Drupal-specific Twig:
  • {{ 'Text'|t }}
    - Translate strings
  • {{ attach_library('theme/library') }}
    - Load CSS/JS
  • {{ url('route.name') }}
    - Generate URLs
  • {{ path('route.name') }}
    - Generate paths
  • {{ file_url('public://image.jpg') }}
    - File URLs
  • {{ content|without('field') }}
    - Exclude fields
Common templates:
  • page.html.twig
    - Page layout structure
  • node.html.twig
    - Node display
  • block.html.twig
    - Block rendering
  • field.html.twig
    - Field output
  • views-view.html.twig
    - Views output
掌握Twig语法和Drupal专属扩展:
Twig基础:
  • {{ variable }}
    - 打印变量
  • {% if/for/set %}
    - 控制结构和逻辑
  • {# comment #}
    - 注释和文档
  • {{ var|filter }}
    - 为变量应用过滤器
  • {% extends %}
    - 模板继承
  • {% block %}
    - 定义可覆写的区块
Drupal专属Twig语法:
  • {{ 'Text'|t }}
    - 字符串翻译
  • {{ attach_library('theme/library') }}
    - 加载CSS/JS
  • {{ url('route.name') }}
    - 生成URL
  • {{ path('route.name') }}
    - 生成路径
  • {{ file_url('public://image.jpg') }}
    - 生成文件URL
  • {{ content|without('field') }}
    - 排除指定字段
常用模板:
  • page.html.twig
    - 页面布局结构
  • node.html.twig
    - 内容展示
  • block.html.twig
    - 区块渲染
  • field.html.twig
    - 字段输出
  • views-view.html.twig
    - Views输出

3. Preprocessing Functions

3. 预处理函数

Modify template variables before rendering:
Preprocess pattern:
php
function THEMENAME_preprocess_HOOK(&$variables) {
  // Add or modify variables
  // Access entities, services, configuration
  // Prepare data for templates
}
Common preprocess hooks:
  • hook_preprocess_page()
    - Page-level variables
  • hook_preprocess_node()
    - Node-specific data
  • hook_preprocess_block()
    - Block modifications
  • hook_preprocess_field()
    - Field alterations
  • hook_preprocess_html()
    - HTML document
Best practices:
  • Keep logic in preprocess, markup in templates
  • Use dependency injection when possible
  • Cache properly with cache contexts/tags
  • Document complex preprocessing
在渲染前修改模板变量:
预处理模式:
php
function THEMENAME_preprocess_HOOK(&$variables) {
  // 添加或修改变量
  // 访问实体、服务、配置
  // 为模板准备数据
}
常用预处理hook:
  • hook_preprocess_page()
    - 页面级变量
  • hook_preprocess_node()
    - 内容专属数据
  • hook_preprocess_block()
    - 区块修改
  • hook_preprocess_field()
    - 字段变更
  • hook_preprocess_html()
    - HTML文档处理
最佳实践:
  • 逻辑放在预处理中,标记放在模板中
  • 尽可能使用依赖注入
  • 使用缓存上下文/标签做好缓存配置
  • 为复杂的预处理逻辑编写文档

4. Template Suggestions

4. 模板建议

Provide specific templates for different contexts:
Suggestion patterns:
page--front.html.twig                  # Homepage
page--node--{nid}.html.twig            # Specific node
page--node--{type}.html.twig           # Content type
node--{type}--{viewmode}.html.twig     # Type + view mode
block--{plugin-id}.html.twig           # Specific block
field--{entity}--{field}.html.twig     # Specific field
Adding suggestions:
php
function THEMENAME_theme_suggestions_HOOK_alter(array &$suggestions, array $variables) {
  // Add custom suggestions
  $suggestions[] = 'custom__suggestion';
}
为不同场景提供专属模板:
建议规则:
page--front.html.twig                  # 首页
page--node--{nid}.html.twig            # 指定ID的内容
page--node--{type}.html.twig           # 指定内容类型
node--{type}--{viewmode}.html.twig     # 内容类型+展示模式
block--{plugin-id}.html.twig           # 指定区块
field--{entity}--{field}.html.twig     # 指定字段
添加自定义建议:
php
function THEMENAME_theme_suggestions_HOOK_alter(array &$suggestions, array $variables) {
  // 添加自定义建议
  $suggestions[] = 'custom__suggestion';
}

5. CSS & JavaScript Management

5. CSS与JavaScript管理

Organize and load theme assets efficiently:
Library definition:
yaml
undefined
高效组织和加载主题资源:
库定义示例:
yaml
undefined

THEMENAME.libraries.yml

THEMENAME.libraries.yml

global-styling: version: 1.0 css: base: css/base/reset.css: {} theme: css/theme/styles.css: {} js: js/custom.js: {} dependencies: - core/drupal

**Loading libraries:**
- Global: Define in `.info.yml`
- Conditional: Use `attach_library()` in templates
- Preprocessed: Attach in preprocess functions

**Best practices:**
- Separate CSS into layers (base, layout, component, theme)
- Use CSS aggregation in production
- Minimize JavaScript dependencies
- Leverage Drupal's asset library system
global-styling: version: 1.0 css: base: css/base/reset.css: {} theme: css/theme/styles.css: {} js: js/custom.js: {} dependencies: - core/drupal

**加载库的方式:**
- 全局加载:在 `.info.yml` 中定义
- 条件加载:在模板中使用 `attach_library()`
- 预处理加载:在预处理函数中挂载

**最佳实践:**
- 将CSS分层(基础层、布局层、组件层、主题层)
- 生产环境启用CSS聚合
- 最小化JavaScript依赖
- 充分利用Drupal的资源库系统

6. Responsive Design

6. 响应式设计

Implement mobile-first, accessible designs:
Breakpoints definition:
yaml
undefined
实现移动端优先、可访问的设计:
断点定义示例:
yaml
undefined

THEMENAME.breakpoints.yml

THEMENAME.breakpoints.yml

THEMENAME.mobile: label: Mobile mediaQuery: 'screen and (min-width: 0px)' weight: 0
THEMENAME.tablet: label: Tablet mediaQuery: 'screen and (min-width: 768px)' weight: 1
THEMENAME.desktop: label: Desktop mediaQuery: 'screen and (min-width: 1024px)' weight: 2

**Mobile-first approach:**
1. Design for smallest screens first
2. Enhance for larger viewports
3. Use responsive images
4. Test across devices
5. Follow accessibility standards (WCAG)
THEMENAME.mobile: label: Mobile mediaQuery: 'screen and (min-width: 0px)' weight: 0
THEMENAME.tablet: label: Tablet mediaQuery: 'screen and (min-width: 768px)' weight: 1
THEMENAME.desktop: label: Desktop mediaQuery: 'screen and (min-width: 1024px)' weight: 2

**移动端优先方案:**
1. 优先为最小屏幕设计
2. 针对更大视口做增强
3. 使用响应式图片
4. 跨设备测试
5. 遵循可访问性标准(WCAG)

Development Workflow

开发工作流

Creating a New Theme

创建新主题

  1. Scaffold the theme:
    bash
    cp -r assets/theme-template/ /path/to/drupal/themes/custom/mytheme/
    cd /path/to/drupal/themes/custom/mytheme/
    
    # Rename files
    mv THEMENAME.info.yml mytheme.info.yml
    mv THEMENAME.libraries.yml mytheme.libraries.yml
    mv THEMENAME.theme mytheme.theme
  2. Update theme configuration:
    • Edit
      mytheme.info.yml
      - Set name, regions, base theme
    • Edit
      mytheme.libraries.yml
      - Define CSS/JS libraries
    • Replace
      THEMENAME
      with your machine name
    • Replace
      THEMELABEL
      with your label
  3. Enable the theme:
    bash
    ddev drush cr
    # Enable via UI at /admin/appearance or:
    ddev drush config:set system.theme default mytheme -y
  4. Enable Twig debugging:
    • Copy
      sites/default/default.services.yml
      to
      sites/default/services.yml
    • Set
      twig.config.debug: true
    • Set
      twig.config.auto_reload: true
    • Set
      twig.config.cache: false
    • Run
      ddev drush cr
  5. Develop and iterate:
    • Modify templates in
      templates/
    • Update CSS in
      css/
    • Clear cache frequently:
      ddev drush cr
    • Check browser console for errors
  1. 生成主题脚手架:
    bash
    cp -r assets/theme-template/ /path/to/drupal/themes/custom/mytheme/
    cd /path/to/drupal/themes/custom/mytheme/
    
    # 重命名文件
    mv THEMENAME.info.yml mytheme.info.yml
    mv THEMENAME.libraries.yml mytheme.libraries.yml
    mv THEMENAME.theme mytheme.theme
  2. 更新主题配置:
    • 编辑
      mytheme.info.yml
      - 设置名称、区域、基础主题
    • 编辑
      mytheme.libraries.yml
      - 定义CSS/JS库
    • 将所有
      THEMENAME
      替换为你的主题机器名
    • 将所有
      THEMELABEL
      替换为你的主题展示名
  3. 启用主题:
    bash
    ddev drush cr
    # 可通过 /admin/appearance UI启用,或执行以下命令:
    ddev drush config:set system.theme default mytheme -y
  4. 开启Twig调试:
    • 复制
      sites/default/default.services.yml
      sites/default/services.yml
    • 设置
      twig.config.debug: true
    • 设置
      twig.config.auto_reload: true
    • 设置
      twig.config.cache: false
    • 执行
      ddev drush cr
  5. 开发与迭代:
    • 修改
      templates/
      目录下的模板
    • 更新
      css/
      目录下的样式
    • 频繁清理缓存:
      ddev drush cr
    • 检查浏览器控制台是否有报错

Standard Development Workflow

标准开发工作流

  1. Enable development settings (Twig debug, disable CSS/JS aggregation)
  2. Create/modify templates based on suggestions from Twig debug
  3. Implement preprocessing in
    .theme
    file for complex data manipulation
  4. Add CSS/JS via libraries system
  5. Test across browsers and devices
  6. Clear cache after changes:
    ddev drush cr
  1. 开启开发设置(Twig调试、禁用CSS/JS聚合)
  2. 根据Twig调试给出的建议创建/修改模板
  3. .theme
    文件中实现预处理逻辑
    ,处理复杂数据
  4. 通过资源库系统添加CSS/JS
  5. 跨浏览器和设备测试
  6. 变更后清理缓存
    ddev drush cr

Finding Template Names

查找模板名称

With Twig debugging enabled, inspect HTML source:
html
<!-- FILE NAME SUGGESTIONS:
   * page--node--123.html.twig
   * page--node--article.html.twig
   * page--node.html.twig
   x page.html.twig
-->
The
x
indicates the active template. Others are suggestions you can create.
开启Twig调试后,查看HTML源码即可看到:
html
<!-- FILE NAME SUGGESTIONS:
   * page--node--123.html.twig
   * page--node--article.html.twig
   * page--node.html.twig
   x page.html.twig
-->
x
标记的是当前生效的模板,其他是你可以创建的可选模板建议。

Common Patterns

常用模式

Adding Custom Variables in Preprocess

在预处理中添加自定义变量

php
function mytheme_preprocess_page(&$variables) {
  // Add site slogan
  $variables['site_slogan'] = \Drupal::config('system.site')->get('slogan');

  // Add current user
  $variables['is_logged_in'] = \Drupal::currentUser()->isAuthenticated();

  // Add custom class
  $variables['attributes']['class'][] = 'custom-page-class';
}
php
function mytheme_preprocess_page(&$variables) {
  // 添加站点标语
  $variables['site_slogan'] = \Drupal::config('system.site')->get('slogan');

  // 添加当前用户登录状态
  $variables['is_logged_in'] = \Drupal::currentUser()->isAuthenticated();

  // 添加自定义类
  $variables['attributes']['class'][] = 'custom-page-class';
}

Template Inheritance

模板继承

twig
{# templates/page--article.html.twig #}
{% extends "page.html.twig" %}

{% block content %}
  <div class="article-wrapper">
    {{ parent() }}
  </div>
{% endblock %}
twig
{# templates/page--article.html.twig #}
{% extends "page.html.twig" %}

{% block content %}
  <div class="article-wrapper">
    {{ parent() }}
  </div>
{% endblock %}

Conditional Library Loading

条件加载资源库

php
function mytheme_preprocess_node(&$variables) {
  if ($variables['node']->bundle() == 'article') {
    $variables['#attached']['library'][] = 'mytheme/article-styles';
  }
}
php
function mytheme_preprocess_node(&$variables) {
  if ($variables['node']->bundle() == 'article') {
    $variables['#attached']['library'][] = 'mytheme/article-styles';
  }
}

Accessing Field Values in Twig

在Twig中访问字段值

twig
{# Get field value #}
{{ node.field_custom.value }}

{# Check if field has value #}
{% if node.field_image|render %}
  {{ content.field_image }}
{% endif %}

{# Loop through multi-value field #}
{% for item in node.field_tags %}
  {{ item.entity.label }}
{% endfor %}
twig
{# 获取字段值 #}
{{ node.field_custom.value }}

{# 判断字段是否有值 #}
{% if node.field_image|render %}
  {{ content.field_image }}
{% endif %}

{# 遍历多值字段 #}
{% for item in node.field_tags %}
  {{ item.entity.label }}
{% endfor %}

Best Practices

最佳实践

Theme Development

主题开发

  1. Base theme: Choose appropriate base (Olivero, Claro, or none)
  2. Structure: Organize CSS logically (base, layout, components, theme)
  3. Naming: Use BEM or similar CSS methodology
  4. Comments: Document complex Twig logic and preprocessing
  5. Performance: Optimize images, minimize CSS/JS, lazy load when possible
  1. 基础主题:选择合适的基础主题(Olivero、Claro,或不使用基础主题)
  2. 结构:逻辑清晰地组织CSS(基础、布局、组件、主题)
  3. 命名:使用BEM或类似的CSS命名规范
  4. 注释:为复杂的Twig逻辑和预处理逻辑编写文档
  5. 性能:优化图片、最小化CSS/JS体积、按需使用懒加载

Twig Templates

Twig模板

  1. Logic: Keep complex logic in preprocess, not templates
  2. Filters: Use appropriate filters (|t, |clean_class, |safe_join)
  3. Whitespace: Use {% spaceless %} to control output
  4. Debugging: Enable Twig debugging during development only
  5. Suggestions: Use specific templates only when needed
  1. 逻辑:复杂逻辑放在预处理中,不要放在模板里
  2. 过滤器:使用合适的过滤器(|t、|clean_class、|safe_join)
  3. 空白控制:使用 {% spaceless %} 控制输出的空白字符
  4. 调试:仅在开发阶段开启Twig调试
  5. 模板建议:仅在必要时使用专属模板

Preprocessing

预处理

  1. Services: Use dependency injection in theme service subscribers
  2. Caching: Add proper cache contexts and tags
  3. Performance: Avoid heavy operations in frequently-called preprocessors
  4. Organization: Group related preprocessing logically
  1. 服务:在主题服务订阅者中使用依赖注入
  2. 缓存:添加合适的缓存上下文和标签
  3. 性能:在高频调用的预处理函数中避免重操作
  4. 组织:逻辑相关的预处理代码按组整理

CSS & JavaScript

CSS与JavaScript

  1. Libraries: Group related assets into logical libraries
  2. Dependencies: Declare all library dependencies
  3. Loading: Load globally only when necessary
  4. Aggregation: Enable in production for performance
  1. 库配置:将相关资源整理为逻辑独立的库
  2. 依赖:声明所有库的依赖
  3. 加载规则:仅必要时全局加载资源
  4. 聚合:生产环境启用资源聚合提升性能

Accessibility

可访问性

  1. Semantic HTML: Use proper elements (header, nav, main, etc.)
  2. ARIA: Add labels and roles when needed
  3. Keyboard: Ensure keyboard navigation works
  4. Contrast: Meet WCAG color contrast requirements
  5. Alt text: Provide for all images
  1. 语义化HTML:使用正确的元素(header、nav、main等)
  2. ARIA:按需添加标签和角色
  3. 键盘操作:确保键盘导航可用
  4. 对比度:符合WCAG颜色对比度要求
  5. 替代文本:为所有图片添加alt文本

Responsive Design

响应式设计

  1. Mobile-first: Design for small screens, enhance for large
  2. Breakpoints: Define logical breakpoints
  3. Images: Use responsive image styles
  4. Testing: Test across devices and screen sizes
  5. Performance: Optimize for mobile networks
  1. 移动端优先:先为小屏幕设计,再为大屏幕做增强
  2. 断点:定义符合业务逻辑的断点
  3. 图片:使用响应式图片样式
  4. 测试:跨设备和屏幕尺寸测试
  5. 性能:针对移动网络做优化

Troubleshooting

问题排查

Template Changes Not Showing

模板变更不生效

  • Clear cache:
    ddev drush cr
  • Verify file location and naming
  • Check Twig debug for active template
  • Ensure library is properly defined
  • 清理缓存:
    ddev drush cr
  • 确认文件路径和命名正确
  • 通过Twig调试确认当前生效的模板
  • 确保资源库配置正确

CSS/JS Not Loading

CSS/JS不加载

  • Check library definition in
    .libraries.yml
  • Verify file paths are correct
  • Ensure library is attached (globally or conditionally)
  • Clear cache and check browser console
  • 检查
    .libraries.yml
    中的库定义
  • 确认文件路径正确
  • 确认资源库已被挂载(全局或条件挂载)
  • 清理缓存并检查浏览器控制台

Variables Not Available in Template

模板中无法获取变量

  • Check preprocess function naming
  • Verify variables are being set correctly
  • Use Twig debugging:
    {{ dump() }}
  • Clear cache after preprocessing changes
  • 检查预处理函数的命名是否正确
  • 确认变量已被正确赋值
  • 使用Twig调试工具:
    {{ dump() }}
  • 预处理变更后清理缓存

Twig Debugging Not Working

Twig调试不生效

  • Verify
    sites/default/services.yml
    exists
  • Check
    twig.config.debug: true
    is set
  • Clear cache:
    ddev drush cr
  • Check file permissions
  • 确认
    sites/default/services.yml
    文件存在
  • 检查是否已设置
    twig.config.debug: true
  • 清理缓存:
    ddev drush cr
  • 检查文件权限

Resources

资源

Reference Documentation

参考文档

  • references/theming.md
    - Comprehensive theming guide
    • Twig syntax and filters
    • Template suggestions
    • Preprocessing patterns
    • Library management
    • Responsive design
    • Best practices
  • references/theming.md
    - 完整的主题开发指南
    • Twig语法和过滤器
    • 模板建议
    • 预处理模式
    • 资源库管理
    • 响应式设计
    • 最佳实践

Asset Templates

资源模板

  • assets/theme-template/
    - Complete theme scaffold
    • .info.yml
      with regions and configuration
    • .libraries.yml
      with CSS/JS examples
    • .theme
      with preprocess examples
    • Page template
    • CSS and JS starter files
  • assets/theme-template/
    - 完整的主题脚手架
    • 带区域和配置的
      .info.yml
    • 带CSS/JS示例的
      .libraries.yml
    • 带预处理示例的
      .theme
    • 页面模板
    • CSS和JS启动文件

Searching References

搜索参考命令

bash
undefined
bash
undefined

Find specific Twig filter

查找特定Twig过滤器

grep -r "clean_class" references/
grep -r "clean_class" references/

Find preprocessing examples

查找预处理示例

grep -r "preprocess_node" references/
grep -r "preprocess_node" references/

Find library patterns

查找资源库配置模式

grep -r "libraries.yml" references/
undefined
grep -r "libraries.yml" references/
undefined

Version Compatibility

版本兼容性

Drupal 8 vs 9 vs 10 vs 11

Drupal 8 / 9 / 10 / 11 差异

  • Twig syntax: Consistent across all versions
  • Base themes: Some legacy themes removed in 10+
  • Libraries: Same structure across versions
  • jQuery: Drupal 9+ doesn't load jQuery by default
  • Claro: Admin theme standard in 9+
  • Olivero: Frontend theme standard in 10+
  • Twig语法:所有版本保持一致
  • 基础主题:部分老旧主题在10+版本中被移除
  • 资源库:所有版本结构一致
  • jQuery:Drupal 9+ 默认不加载jQuery
  • Claro:9+版本默认管理主题
  • Olivero:10+版本默认前端主题

Migration Notes

迁移注意事项

  • When upgrading, check for deprecated base themes
  • Review jQuery dependencies
  • Test with current Twig version
  • Check for removed core templates
  • 升级时检查是否使用了已弃用的基础主题
  • 检查jQuery依赖
  • 用当前Twig版本测试
  • 检查是否使用了已被移除的核心模板

See Also

相关内容