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

如何使用自定义模板mypage.html.twig渲染特定页面且不修改HTML主题包装?

解决方案

在Drupal中,要给特定页面替换page.html.twig模板且不影响html.html.twig的主题包装,可按以下步骤操作:

1. 模块内注册自定义模板

  • 在你的模块目录下创建templates文件夹,将自定义的mypage.html.twig模板放入其中。
  • 在模块的.module文件中,通过hook_theme()完成模板注册:
function YOUR_MODULE_theme($existing, $type, $theme, $path) {
  return [
    'mypage' => [
      'variables' => ['content' => NULL], // 根据实际需求定义模板变量
      'template' => 'mypage',
    ],
  ];
}

2. 控制器指定使用自定义模板

修改基于ControllerBase的控制器,不再仅返回内容片段,而是返回包含模板指定的渲染数组:

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Render\Markup;

class YourController extends ControllerBase {
  public function myPage() {
    // 准备模板所需的变量
    $variables = [
      'content' => Markup::create('<p>自定义页面内容</p>'),
      // 可按需添加更多自定义变量
    ];

    // 返回指定模板的渲染数组
    return [
      '#theme' => 'mypage',
      '#variables' => $variables,
    ];
  }
}

3. 替换目标页面的默认page模板

通过hook_preprocess_page()修改页面的模板指向,确保仅目标页面使用自定义模板:

function YOUR_MODULE_preprocess_page(&$variables) {
  // 通过路由名称判断是否为目标页面,替换为你的实际路由名
  $route_name = \Drupal::routeMatch()->getRouteName();
  if ($route_name === 'your_module.target_route') {
    // 将页面模板替换为自定义的mypage
    $variables['#theme'] = 'mypage';
    // 若需要保留原page模板的部分变量,可在此处传递对应数据
  }
}

关键注意事项

  • 自定义模板mypage.html.twig需包含你需要的完整页面结构(如页头、内容区、页脚等),替换后默认page.html.twig不再生效。
  • 修改完成后务必清除Drupal缓存,确保新模板和钩子函数被系统加载。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 17:56:12