drupal-frontend
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDrupal 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:
- Use theme template from as starting point
assets/theme-template/ - Replace with your theme's machine name
THEMENAME - Replace with human-readable name
THEMELABEL - Customize templates, CSS, JS, and libraries
- Enable theme and configure via Appearance UI
Theme components:
- - Theme metadata and configuration
.info.yml - - CSS/JS library definitions
.libraries.yml - - Preprocess functions and theme logic
.theme - - Responsive breakpoints
.breakpoints.yml - - Twig template files
templates/ - - Stylesheets
css/ - - JavaScript files
js/
Reference documentation:
- - Complete theming guide with examples
references/theming.md
构建结构规范、符合标准的完整Drupal主题:
快速启动工作流:
- 以 中的主题模板为起点
assets/theme-template/ - 将 替换为你的主题机器名
THEMENAME - 将 替换为人类可读的主题名称
THEMELABEL - 自定义模板、CSS、JS和库配置
- 启用主题并通过外观UI进行配置
主题组成部分:
- - 主题元数据和配置
.info.yml - - CSS/JS库定义
.libraries.yml - - 预处理函数和主题逻辑
.theme - - 响应式断点配置
.breakpoints.yml - - Twig模板文件
templates/ - - 样式表文件
css/ - - JavaScript文件
js/
参考文档:
- - 带示例的完整主题开发指南
references/theming.md
2. Twig Template System
2. Twig模板系统
Master Twig syntax and Drupal-specific extensions:
Twig fundamentals:
- - Print variables
{{ variable }} - - Control structures and logic
{% if/for/set %} - - Comments and documentation
{# comment #} - - Apply filters to variables
{{ var|filter }} - - Template inheritance
{% extends %} - - Define overridable sections
{% block %}
Drupal-specific Twig:
- - Translate strings
{{ 'Text'|t }} - - Load CSS/JS
{{ attach_library('theme/library') }} - - Generate URLs
{{ url('route.name') }} - - Generate paths
{{ path('route.name') }} - - File URLs
{{ file_url('public://image.jpg') }} - - Exclude fields
{{ content|without('field') }}
Common templates:
- - Page layout structure
page.html.twig - - Node display
node.html.twig - - Block rendering
block.html.twig - - Field output
field.html.twig - - Views output
views-view.html.twig
掌握Twig语法和Drupal专属扩展:
Twig基础:
- - 打印变量
{{ variable }} - - 控制结构和逻辑
{% if/for/set %} - - 注释和文档
{# comment #} - - 为变量应用过滤器
{{ var|filter }} - - 模板继承
{% extends %} - - 定义可覆写的区块
{% block %}
Drupal专属Twig语法:
- - 字符串翻译
{{ 'Text'|t }} - - 加载CSS/JS
{{ attach_library('theme/library') }} - - 生成URL
{{ url('route.name') }} - - 生成路径
{{ path('route.name') }} - - 生成文件URL
{{ file_url('public://image.jpg') }} - - 排除指定字段
{{ content|without('field') }}
常用模板:
- - 页面布局结构
page.html.twig - - 内容展示
node.html.twig - - 区块渲染
block.html.twig - - 字段输出
field.html.twig - - Views输出
views-view.html.twig
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:
- - Page-level variables
hook_preprocess_page() - - Node-specific data
hook_preprocess_node() - - Block modifications
hook_preprocess_block() - - Field alterations
hook_preprocess_field() - - HTML document
hook_preprocess_html()
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() - - HTML文档处理
hook_preprocess_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 fieldAdding 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
undefinedTHEMENAME.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 systemglobal-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
undefinedTHEMENAME.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
创建新主题
-
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 -
Update theme configuration:
- Edit - Set name, regions, base theme
mytheme.info.yml - Edit - Define CSS/JS libraries
mytheme.libraries.yml - Replace with your machine name
THEMENAME - Replace with your label
THEMELABEL
- Edit
-
Enable the theme:bash
ddev drush cr # Enable via UI at /admin/appearance or: ddev drush config:set system.theme default mytheme -y -
Enable Twig debugging:
- Copy to
sites/default/default.services.ymlsites/default/services.yml - Set
twig.config.debug: true - Set
twig.config.auto_reload: true - Set
twig.config.cache: false - Run
ddev drush cr
- Copy
-
Develop and iterate:
- Modify templates in
templates/ - Update CSS in
css/ - Clear cache frequently:
ddev drush cr - Check browser console for errors
- Modify templates in
-
生成主题脚手架: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 -
更新主题配置:
- 编辑 - 设置名称、区域、基础主题
mytheme.info.yml - 编辑 - 定义CSS/JS库
mytheme.libraries.yml - 将所有 替换为你的主题机器名
THEMENAME - 将所有 替换为你的主题展示名
THEMELABEL
- 编辑
-
启用主题:bash
ddev drush cr # 可通过 /admin/appearance UI启用,或执行以下命令: ddev drush config:set system.theme default mytheme -y -
开启Twig调试:
- 复制 到
sites/default/default.services.ymlsites/default/services.yml - 设置
twig.config.debug: true - 设置
twig.config.auto_reload: true - 设置
twig.config.cache: false - 执行
ddev drush cr
- 复制
-
开发与迭代:
- 修改 目录下的模板
templates/ - 更新 目录下的样式
css/ - 频繁清理缓存:
ddev drush cr - 检查浏览器控制台是否有报错
- 修改
Standard Development Workflow
标准开发工作流
- Enable development settings (Twig debug, disable CSS/JS aggregation)
- Create/modify templates based on suggestions from Twig debug
- Implement preprocessing in file for complex data manipulation
.theme - Add CSS/JS via libraries system
- Test across browsers and devices
- Clear cache after changes:
ddev drush cr
- 开启开发设置(Twig调试、禁用CSS/JS聚合)
- 根据Twig调试给出的建议创建/修改模板
- 在 文件中实现预处理逻辑,处理复杂数据
.theme - 通过资源库系统添加CSS/JS
- 跨浏览器和设备测试
- 变更后清理缓存:
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 indicates the active template. Others are suggestions you can create.
x开启Twig调试后,查看HTML源码即可看到:
html
<!-- FILE NAME SUGGESTIONS:
* page--node--123.html.twig
* page--node--article.html.twig
* page--node.html.twig
x page.html.twig
-->xCommon 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
主题开发
- Base theme: Choose appropriate base (Olivero, Claro, or none)
- Structure: Organize CSS logically (base, layout, components, theme)
- Naming: Use BEM or similar CSS methodology
- Comments: Document complex Twig logic and preprocessing
- Performance: Optimize images, minimize CSS/JS, lazy load when possible
- 基础主题:选择合适的基础主题(Olivero、Claro,或不使用基础主题)
- 结构:逻辑清晰地组织CSS(基础、布局、组件、主题)
- 命名:使用BEM或类似的CSS命名规范
- 注释:为复杂的Twig逻辑和预处理逻辑编写文档
- 性能:优化图片、最小化CSS/JS体积、按需使用懒加载
Twig Templates
Twig模板
- Logic: Keep complex logic in preprocess, not templates
- Filters: Use appropriate filters (|t, |clean_class, |safe_join)
- Whitespace: Use {% spaceless %} to control output
- Debugging: Enable Twig debugging during development only
- Suggestions: Use specific templates only when needed
- 逻辑:复杂逻辑放在预处理中,不要放在模板里
- 过滤器:使用合适的过滤器(|t、|clean_class、|safe_join)
- 空白控制:使用 {% spaceless %} 控制输出的空白字符
- 调试:仅在开发阶段开启Twig调试
- 模板建议:仅在必要时使用专属模板
Preprocessing
预处理
- Services: Use dependency injection in theme service subscribers
- Caching: Add proper cache contexts and tags
- Performance: Avoid heavy operations in frequently-called preprocessors
- Organization: Group related preprocessing logically
- 服务:在主题服务订阅者中使用依赖注入
- 缓存:添加合适的缓存上下文和标签
- 性能:在高频调用的预处理函数中避免重操作
- 组织:逻辑相关的预处理代码按组整理
CSS & JavaScript
CSS与JavaScript
- Libraries: Group related assets into logical libraries
- Dependencies: Declare all library dependencies
- Loading: Load globally only when necessary
- Aggregation: Enable in production for performance
- 库配置:将相关资源整理为逻辑独立的库
- 依赖:声明所有库的依赖
- 加载规则:仅必要时全局加载资源
- 聚合:生产环境启用资源聚合提升性能
Accessibility
可访问性
- Semantic HTML: Use proper elements (header, nav, main, etc.)
- ARIA: Add labels and roles when needed
- Keyboard: Ensure keyboard navigation works
- Contrast: Meet WCAG color contrast requirements
- Alt text: Provide for all images
- 语义化HTML:使用正确的元素(header、nav、main等)
- ARIA:按需添加标签和角色
- 键盘操作:确保键盘导航可用
- 对比度:符合WCAG颜色对比度要求
- 替代文本:为所有图片添加alt文本
Responsive Design
响应式设计
- Mobile-first: Design for small screens, enhance for large
- Breakpoints: Define logical breakpoints
- Images: Use responsive image styles
- Testing: Test across devices and screen sizes
- Performance: Optimize for mobile networks
- 移动端优先:先为小屏幕设计,再为大屏幕做增强
- 断点:定义符合业务逻辑的断点
- 图片:使用响应式图片样式
- 测试:跨设备和屏幕尺寸测试
- 性能:针对移动网络做优化
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 exists
sites/default/services.yml - Check is set
twig.config.debug: true - Clear cache:
ddev drush cr - Check file permissions
- 确认 文件存在
sites/default/services.yml - 检查是否已设置
twig.config.debug: true - 清理缓存:
ddev drush cr - 检查文件权限
Resources
资源
Reference Documentation
参考文档
- - Comprehensive theming guide
references/theming.md- Twig syntax and filters
- Template suggestions
- Preprocessing patterns
- Library management
- Responsive design
- Best practices
- - 完整的主题开发指南
references/theming.md- Twig语法和过滤器
- 模板建议
- 预处理模式
- 资源库管理
- 响应式设计
- 最佳实践
Asset Templates
资源模板
- - Complete theme scaffold
assets/theme-template/- with regions and configuration
.info.yml - with CSS/JS examples
.libraries.yml - with preprocess examples
.theme - Page template
- CSS and JS starter files
- - 完整的主题脚手架
assets/theme-template/- 带区域和配置的
.info.yml - 带CSS/JS示例的
.libraries.yml - 带预处理示例的
.theme - 页面模板
- CSS和JS启动文件
- 带区域和配置的
Searching References
搜索参考命令
bash
undefinedbash
undefinedFind 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/
undefinedgrep -r "libraries.yml" references/
undefinedVersion 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
相关内容
- drupal-backend - Module development, hooks, APIs
- drupal-tooling - DDEV and Drush development tools
- Drupal Theming Guide - Official documentation
- Twig Documentation - Twig syntax reference
- drupal-backend - 模块开发、hook、API
- drupal-tooling - DDEV和Drush开发工具
- Drupal主题开发指南 - 官方文档
- Twig文档 - Twig语法参考