我想设置一些全局变量,我需要在 Drupal 8 中的所有主题的 Twig 模板中使用这些变量。
Drupal 7 文档提到预处理功能:
主题名称_预处理 这个是以主题本身命名的。适用于所有挂钩。
所以我将下面的函数添加到我的
themename.theme
文件中,但变量未设置。
function themename_preprocess(&$variables) {
$theme_path = $variables['base_path'] . $variables['directory'];
$variables['theme_path'] = $theme_path;
$variables['images_path'] = $theme_path . "/images/";
$variables['templates_path'] = $theme_path . "/templates/";
}
当我定义
themename_preprocess
(而不是定义 themename_preprocess_page
)(如下)时,变量已正确定义并在 page.html.twig
模板中可用。
function themename_preprocess_page(&$variables) {
$theme_path = $variables['base_path'] . $variables['directory'];
$variables['theme_path'] = $theme_path;
$variables['images_path'] = $theme_path . "/images/";
$variables['templates_path'] = $theme_path . "/templates/";
}
但我希望变量在所有模板中可用,而不是仅在
page.html.twig
中可用。我怎样才能做到这一点?
function themename_preprocess(&$variables) {
// code
}
清除缓存后为我解决了这个问题。
@hipertom,谢谢您的解决方案。