【问题标题】:Drupal 7: How do I get module config settings on to theme file?Drupal 7:如何在主题文件中获取模块配置设置?
【发布时间】:2019-11-01 00:35:20
【问题描述】:

我正在创建一个新模块。我有一个管理面板,我可以在其中设置设置。在我的.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】:

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

    /**
     * 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;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-04
      • 1970-01-01
      相关资源
      最近更新 更多