关于 drupal-render
面向 Drupal 开发者的 Render Arrays 参考,介绍构建渲染数组及处理缓存元数据和标记安全的方法。还涵盖渲染元素、延迟构建器和程序化渲染。
主要功能
- 01构建渲染数组
- 02设置缓存标签与上下文
- 03安全处理标记内容
- 04使用渲染元素与延迟构建器
- 05通过渲染器生成输出
适用场景
- 01为动态内容配置缓存
- 02安全呈现用户输入
- 03以代码构建 Drupal 页面内容
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ edutrul/ drupal-ai --skill drupal-render安装后在 Claude Code 中输入/drupal-render确认已加载。
附带文件README.md
详细介绍
Drupal 渲染数组
基本结构
$build = [
'#type' => 'container',
'#attributes' => ['class' => ['my-wrapper']],
'content' => [
'#markup' => $this->t('Hello world'),
],
];
缓存元数据(始终必需)
$build['content'] = [
'#markup' => $output,
'#cache' => [
'tags' => ['node:' . $node->id(), 'node_list'],
'contexts' => ['user.permissions', 'url.query_args'],
'max-age' => 3600,
],
];
缓存标签约定
| 标签 | 失效条件 |
|---|---|
node:123 | 保存节点 123 时 |
node_list | 创建或删除任何节点时 |
user:456 | 保存用户 456 时 |
taxonomy_term:789 | 保存术语 789 时 |
config:my_module.settings | 保存配置时 |
block_content:1 | 保存区块内容时 |
缓存上下文
| 上下文 | 变化依据 |
|---|---|
user | 当前用户身份 |
user.permissions | 用户权限 |
user.roles | 用户角色 |
url | 完整 URL |
url.path | 仅 URL 路径 |
url.query_args | 查询字符串 |
languages | 当前语言 |
session | 会话数据 |
theme | 活动主题 |
标记安全性
// Plain text — always safe
$build['#plain_text'] = $user_input;
// Trusted markup — use Markup class
use Drupal\Core\Render\Markup;
$build['#markup'] = Markup::create('<strong>Safe</strong>');
// User input in markup — filter first
use Drupal\Component\Utility\Xss;
$build['#markup'] = Markup::create(Xss::filter($user_input));
// Admin-level markup — allows more tags
$build['#markup'] = Markup::create(Xss::filterAdmin($html));
渲染元素
// HTML tag
$build['heading'] = [
'#type' => 'html_tag',
'#tag' => 'h2',
'#value' => $this->t('Title'),
'#attributes' => ['class' => ['my-heading']],
];
// Link
$build['link'] = [
'#type' => 'link',
'#title' => $this->t('Go'),
'#url' => Url::fromRoute('entity.node.canonical', ['node' => $nid]),
'#attributes' => ['class' => ['button']],
];
// Entity view
$build['node'] = $this->entityTypeManager
->getViewBuilder('node')
->view($node, 'teaser');
// Inline template
$build['inline'] = [
'#type' => 'inline_template',
'#template' => '<div class="{{ class }}">{{ content }}</div>',
'#context' => ['class' => 'my-class', 'content' => $content],
];
延迟构建器(不可缓存的内容)
$build['dynamic'] = [
'#lazy_builder' => [
'my_module.service:buildDynamicContent',
[$arg1, $arg2],
],
'#create_placeholder' => TRUE,
];
以编程方式渲染
// Inject renderer service
public function __construct(
private readonly RendererInterface $renderer,
) {}
// Render to string
$html = $this->renderer->render($build);
// Render in isolated context (doesn't bubble cache)
$html = $this->renderer->renderInIsolation($build);
评论
支持 Markdown