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

Drupal 9中自定义预处理钩子变量无法传递至包含模板的问题

解决Drupal中include模板时预处理变量不生效的问题

核心原因

用{% include %}直接引用模板文件时,Drupal不会自动触发对应的[theme]_preprocess_example__p1预处理函数——因为include只是直接加载模板内容,没有经过主题钩子的完整渲染流程,预处理函数是绑定到**主题钩子(由hook_theme()定义)**上,而非直接绑定到模板文件。

解决方案

方案1:改用theme()函数渲染(推荐)

通过theme()调用主题钩子,会自动触发对应的预处理函数,步骤如下:

  1. 定义主题钩子:在模块(如example.module)或主题的.theme文件中添加hook_theme():
function example_theme() {
  return [
    'example__p1' => [
      'template' => 'example--p1',
      'path' => drupal_get_path('theme', '[你的主题名]') . '/directory',
      'variables' => [
        'name' => '',
        'text' => '',
        'data' => [],
      ],
    ],
  ];
}
  1. 保留/完善预处理函数:在主题的.theme文件中确保预处理逻辑正确:
function [你的主题名]_preprocess_example__p1(&$variables) {
  $variables['name'] = '测试名称';
  $variables['text'] = '这是要显示的文本';
  $variables['data'] = ['key' => 'value'];
}
  1. 替换include为theme()调用:在page--front.html.twig中修改:
{{ theme('example__p1') }}
  1. 清理Drupal缓存:执行缓存清理操作(后台配置→性能→清空所有缓存,或用Drush命令drush cr)。

方案2:坚持用include时手动传递变量

如果必须使用include,可以从父模板传递预处理后的变量:

  1. 在page的预处理中定义变量:在主题的.theme文件中添加:
function [你的主题名]_preprocess_page(&$variables) {
  // 仅在首页加载时定义变量
  if ($variables['is_front']) {
    $variables['example_p1_data'] = [
      'name' => '测试名称',
      'text' => '这是要显示的文本',
      'data' => ['key' => 'value'],
    ];
  }
}
  1. include时传递变量:在page--front.html.twig中修改:
{% include '@[你的主题名]/directory/example--p1.html.twig' with example_p1_data %}

关键检查项

  • 确保模板文件名example--p1.html.twig与主题钩子example__p1的命名规则匹配(Drupal中双破折号对应钩子的双下划线)。
  • hook_theme()中的path参数必须指向模板文件所在的正确目录(主题或模块路径)。
  • 每次修改hook_theme()或预处理函数后,必须清理缓存,否则变更不会生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 01:25:21