滚动
包含模板的一部分
许多开发者更喜欢将页眉 / 页脚的代码保存在单独的文件中,并在 page.html.twig 中调用该文件。
过程
假设你在主题文件夹中为页眉创建了以下文件:
THEME_NAME/templates/includes/header.html.twig
现在你想在以下文件中包含它:
page.html.twig
推荐方法
Drupal 8 主题的正确方法是使用 Twig 命名空间来声明当前主题的 "templates" 目录。示例如下:
{% include '@THEME_NAME/includes/header.html.twig' %}
下面的示例来自 Drupal.org 上的一个实际主题,名为 Architect。
“@architect” 指的是工作主题 (architect) 的 /templates 目录。
{% include '@architect/includes/header.html.twig' %}
Twig 命名空间在 Drupal 8 中会在安装主题时自动创建,并指向主题的 /templates 目录。基本上,在 Twig 包含语句中写 “@theme_name”(如上所示),将会引用服务器上 “your_site.com/themes/theme_name/templates” 的位置。
不推荐的方法
一种可能(但不推荐)的方法是使用以下代码来包含该文件。
{# NOT recommended #}
{% include directory ~ '/templates/includes/header.html.twig' %}
上面的方式可能会工作,但在使用子主题时会导致服务器错误。
扩展命名空间功能
组件库模块 为 Drupal 8 中的 twig 模板提供了更灵活、更复杂的组织方式,它可以与 twig "embed" 一起使用。