Drupal 11 主题制作是一个将设计与功能结合的过程,以下是一个全面的教程指南:
1. 准备工作
系统要求
确保已安装 Drupal 11
PHP 8.1 或更高版本
Composer (用于依赖管理)
创建主题目录
在 /themes/custom/ 下创建你的主题文件夹,例如 mytheme
2. 基本主题结构
mytheme/
├── mytheme.info.yml # 主题元数据
├── mytheme.libraries.yml # CSS/JS 资源
├── mytheme.theme # PHP 逻辑
├── templates/ # Twig 模板
├── src/ # PHP 类
│ └── Plugin/
│ └── Block/ # 自定义区块
├── assets/
│ ├── css/
│ ├── js/
│ └── images/
└── config/ # 配置架构
└── install/
3. 创建主题信息文件 (mytheme.info.yml)
name: 'My Theme'
type: theme
description: 'Custom Drupal 11 theme'
core_version_requirement: ^11
base theme: olivero # 或 classy/stark
libraries:
- mytheme/global-styling
regions:
header: 'Header'
content: 'Content'
sidebar: 'Sidebar'
footer: 'Footer'
4. 添加 CSS 和 JavaScript (mytheme.libraries.yml)
global-styling:
version: 1.0
css:
theme:
assets/css/style.css: {}
js:
assets/js/script.js: {}
dependencies:
- core/jquery
- core/drupal
5. 创建基础模板
page.html.twig (在 templates 目录中)
<!DOCTYPE html>
<html{{ html_attributes }}>
<head>
<head-placeholder token="{{ placeholder_token }}">
<title>{{ head_title|safe_join(' | ') }}</title>
<css-placeholder token="{{ placeholder_token }}">
<js-placeholder token="{{ placeholder_token }}">
</head>
<body{{ attributes }}>
{{ page_top }}
{{ page }}
{{ page_bottom }}
<js-bottom-placeholder token="{{ placeholder_token }}">
</body>
</html>
6. 主题开发最佳实践
使用 Twig 调试
在 sites/default/services.yml 中启用调试:
parameters:
twig.config:
debug: true
auto_reload: true
cache: false
子主题创建
如果你想基于现有主题:
name: 'My Subtheme'
type: theme
description: 'Subtheme of Olivero'
core_version_requirement: ^11
base theme: olivero
7. 响应式设计
在 mytheme.libraries.yml 中添加:
responsive:
css:
theme:
assets/css/responsive.css:
media: 'all and (max-width: 768px)'
8. 主题预处理函数 (mytheme.theme)
<?php
/**
* Implements hook_preprocess_page().
*/
function mytheme_preprocess_page(&$variables) {
// 添加自定义变量到模板
$variables['custom_variable'] = 'Hello Drupal 11!';
}
9. 编译前端资源 (可选)
如果你使用 Sass/LESS 等预处理器:
安装 Node.js 和 npm/yarn
创建 package.json 文件
设置构建脚本
10. 启用主题
访问 /admin/appearance
找到你的主题并点击"安装并设为默认"
高级主题功能
创建自定义区块
在 src/Plugin/Block/ 下创建 PHP 类
主题设置表单
实现 hook_form_system_theme_settings_alter()
使用布局构建器
创建自定义布局模板和样式
调试工具
使用 Devel 模块
Twig 调试工具 ({{ dump(variable) }})
Chrome PHP 调试器
性能优化
聚合 CSS/JS
使用缓存
优化图片资源
延迟加载非关键资源
这个教程涵盖了 Drupal 11 主题制作的基础知识。随着你的需求增长,可以探索更高级的主题技术如组件化主题、使用 Storybook 等前端工具集成。
评论