logo

额外区块类型 (EBT) - 全新的布局构建器体验❗

额外区块类型 (EBT) - 样式化、可定制的区块类型:幻灯片、标签页、卡片、手风琴等更多类型。内置背景、DOM Box、JavaScript 插件的设置。立即体验布局构建的未来。

演示 EBT 模块 下载 EBT 模块

❗额外段落类型 (EPT) - 全新的 Paragraphs 体验

额外段落类型 (EPT) - 类似的基于 Paragraph 的模块集合。

演示 EPT 模块 滚动

滚动

在任意模板中插入区块(Drupal insert block into template)

11/10/2025, by Ivan

Drupal 8

在 Twig 模板中不能直接调用 PHP 代码,因此我们需要将已生成的区块从预处理函数传递到模板中。如果你想在节点模板中传递变量,可以在主题中使用 themename_preprocess_node() 函数;如果是页面模板,则使用 themename_preprocess_page()。通过这些函数将变量传递给 Twig 模板后,就可以在模板中输出该变量。

通过后台创建的区块

$block = \Drupal\block\Entity\Block::load('your_block_id');
$variables['block_output'] = \Drupal::entityTypeManager()
  ->getViewBuilder('block')
  ->view($block);

themename_preprocess_node()(节点模板)函数中可以这样输出区块:

function themename_preprocess_node(&$variables) {
  $block = \Drupal\block\Entity\Block::load('your_block_id');
  $variables['block_output'] = \Drupal::entityTypeManager()
    ->getViewBuilder('block')
    ->view($block);
}

然后在 node.html.twig 模板中输出区块:

{{ block_output }}

通过插件创建的区块

这些区块的调用方式与后台创建的区块类似,只是输出代码略有不同:

$block_manager = \Drupal::service('plugin.manager.block');
// 在这里可以为区块定义自定义配置。
$config = [];
$plugin_block = $block_manager->createInstance('system_breadcrumb_block', $config);
// 某些区块可能有访问权限限制。
$access_result = $block_plugin->access(\Drupal::currentUser());
// 如果无访问权限,返回空数组。
if ($access_result->isForbidden()) {
  return [];
}
$render = $plugin_block->build();
// 此处可根据需要添加缓存标签或上下文。
// 也可在 render()、::getCacheTags、::getCacheContexts 方法中添加缓存标签和上下文。
return $render;

无注释版本的代码:

$block_manager = \Drupal::service('plugin.manager.block');
$config = [];
$plugin_block = $block_manager->createInstance('system_breadcrumb_block', $config);
$access_result = $block_plugin->access(\Drupal::currentUser());
if ($access_result->isForbidden()) {
  return [];
}
$render = $plugin_block->build();
return $render;

Drupal 7

在 Drupal 7 中,功能类似,只是参数稍有不同。我们使用 block_view 而不是 blockview 两个参数:

print render(module_invoke('block', 'block_view', '12'));

如果插入的是 Views 生成的区块,代码如下:

print render(module_invoke('views', 'block_view', 'feedbacks-block'));

在 Drupal 7 中插入 Views 区块时,注意区块的 delta 不再使用数字,而是直接写为 feedbacks-block

Drupal 6

在 Drupal 6 中,要将区块插入到页面的任意位置,请使用 module_invoke() 函数:

$block = module_invoke('views', 'block', 'view', 'block_name');
print $block['content'];

例如,如果要插入一个通过后台创建的区块,使用以下代码:

$block = module_invoke('block', 'block', 'view', 12);
print $block['content'];

这里的 12 是区块的编号(delta)。

如果要插入 Views 生成的区块,写法如下:

$block = module_invoke('views', 'block', 'view', 'feedbacks-block_1');
print $block['content'];

其中 feedbacks-block_1 表示区块名称:feedbacks 是 View 的机器名,block_1 是该 View 中的显示名称(display ID)。