You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Drupal 11的frontrow1区域创建自定义区块模板?

Drupal 11 为指定区域区块创建自定义布局的正确方法

一、修复区块区域信息获取逻辑

你之前的hook_preprocess_block()代码错误在于区域信息的存储路径,Drupal 11中区块所属区域的信息不在$variables['elements']['#configuration']['region'],而是存放在$variables['elements']['#region']。修改后的代码如下:

/**
 * Implements hook_preprocess_block().
 */
function YOURTHEME_preprocess_block(array &$variables) {
  // 获取区块所属区域
  if (isset($variables['elements']['#region'])) {
    $variables['region'] = $variables['elements']['#region'];
  }
  else {
    $variables['region'] = NULL;
  }
}

修改后清除缓存,即可在block.html.twig中通过{{ region }}正确输出区块所属区域名称。

二、创建frontrow1区域专属区块模板

Drupal 11的模板命名规则与Drupal 7不同,直接使用block--frontrow1.html.twig无法被系统识别,需要通过模板建议实现:

方法1:添加自定义模板建议

在主题的.theme文件中添加以下代码,为frontrow1区域的区块生成专属模板建议:

/**
 * Implements hook_theme_suggestions_block_alter().
 */
function YOURTHEME_theme_suggestions_block_alter(array &$suggestions, array $variables) {
  // 为frontrow1区域的区块添加模板建议
  if (isset($variables['elements']['#region']) && $variables['elements']['#region'] === 'frontrow1') {
    $suggestions[] = 'block__frontrow1';
  }
}

方法2:创建并使用专属模板

清除Drupal缓存后,在主题的templates目录下创建block--frontrow1.html.twig文件,可基于主题原有block.html.twig修改,比如添加Bootstrap 5布局类:

{# 继承基础区块模板(可选) #}
{% extends "@YOURTHEME/block.html.twig" %}

{# 重写区块内容区域,添加自定义布局样式 #}
{% block content %}
  <div class="frontrow1-block col-md-4 p-3 border rounded">
    {{ parent() }}
  </div>
{% endblock %}

三、关键注意事项

  • 每次修改.theme文件或新增模板后,必须清除Drupal缓存(路径:配置 → 性能 → 清除所有缓存),否则系统无法识别新逻辑。
  • 确保Bootstrap 5子主题的.info.yml文件中正确声明了templates目录路径,保证模板能被加载。

内容的提问来源于stack exchange,提问作者Finduilas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 16:12:08