mcpField
D
drupal-render

drupal-render

github.com/edutrul开发7349 次安装21 周前更新
代码仓库

关于 drupal-render

面向 Drupal 开发者的 Render Arrays 参考,介绍构建渲染数组及处理缓存元数据和标记安全的方法。还涵盖渲染元素、延迟构建器和程序化渲染。

主要功能

  1. 01构建渲染数组
  2. 02设置缓存标签与上下文
  3. 03安全处理标记内容
  4. 04使用渲染元素与延迟构建器
  5. 05通过渲染器生成输出

适用场景

  1. 01为动态内容配置缓存
  2. 02安全呈现用户输入
  3. 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