我认为最好将您的设置与主题分离。主题用户(即调用主题的代码)应加载配置并通过变量注入模板。
/**
* Implements hook_theme().
*/
function mymodule_theme() {
return [
'mymodule_wrapper' => [
'template' => 'theme/mymodule-wrapper',
'variables' => [
'foo' => NULL,
],
];
}
/**
* Some other module implemented this hook_menu callback for a random path.
*/
function othermodule_random_endpoint() {
$config = variable_get('mymodule_settings', []);
return [
'#theme' => 'mymodule_wrapper',
'#foo' => $config['foo'] ?? NULL,
]
}
但如果你真的需要将变量直接加载到你的模板文件中,有两种方法:
在 Theme File Direct 中加载设置
Drupal 7 中的所有主题文件都是 php 文件(如后缀 .tpl.php 所建议的那样)。我不推荐它,但你完全可以这样做。在您的主题文件中:
<?php
// load the configs here
$config = variable_get('mymodule_settings', []);
?>
<div>
<p>Hello, this is a config value: <?php echo $config['foo']; ?></p>
</div>
这很难看,但很有效。
使用 hook_preprocess_HOOK
第二种方法是实现hook_preprocess_HOOK。
/**
* Implements hook_theme().
*/
function mymodule_theme() {
return [
'mymodule_wrapper' => [
'template' => 'theme/mymodule-wrapper',
'variables' => [
'foo' => NULL,
],
];
}
/**
* Implements hook_preprocess_HOOK
*/
function mymodule_preprocess_mymodule_wrapper(&$variables) {
if (!isset($variables['config'])) {
$config = variable_get('mymodule_settings', []);
$variables['foo'] = $config['foo'] ?? NULL;
}
}