Drupal 7:如何在主题文件上获取模块配置设置?

问题描述 投票:0回答:1

我正在创建一个新模块。我有一个管理面板,可以在其中设置设置。在我的.module文件中,可以使用$config = variable_get('mymodule_settings', []);检索这些设置。

我正在使用hook_theme()声明主题:

/**
 * Implements hook_theme().
 */
function fcl_trustpilot_theme() {
  return [
    'mymodule_wrapper' => [
      'template' => 'theme/mymodule-wrapper',
      'variables' => [],
    ]
}

但是如何从mymodule_settings中获取数据以显示在theme/mymodule-wrapper文件中?

php drupal drupal-7
1个回答
0
投票

我认为最好将设置与主题脱钩。主题用户(即调用您主题的代码)应加载配置并通过变量注入模板。

/**
 * 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,
  ]
}

但是如果您确实需要将变量直接加载到模板文件中,则有两种方法:

直接在主题文件中加载设置

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;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.