Drupal 7:hook_block_view()发送后,数据没有出现在块的.tpl文件中

时间:2018-03-21 06:06:36

标签: drupal drupal-7

我从配置表单中获取数据并将其传递给.tpl文件进行显示。

我正在使用hook_block_view()获取数据,将其放入数组并将其发送到.tpl文件。

我的代码(在.module上)是这样的:

/**
 * Implements hook_block_info().
 */
function message_block_info() {
  return [
    'message_block' => [
      'info' => t('Message'),
      'cache' => DRUPAL_CACHE_GLOBAL,
    ],
  ];
}

/**
 * Implements hook_theme().
 */
function message_theme() {
  return [
    'message_block' => [
      'template' => 'templates/message-block',
      'variables' => [
        'settings' => NULL,
        'attributes' => [],
      ],
    ],
  ];
}

/**
 * Implements hook_block_view().
 */
function message_block_view($delta = '') {
  if ($delta !== 'message_block') {
    return;
  }

  $config = message_default_settings();

  dpm($config); // <- this shows correct data

  $block['content'] = array(
    '#theme' => 'message_block',
    '#config' => array(
      'message_text' => filter_xss($config['message_text']),
      'message_link' => filter_xss($config['message_link']),
      'message_button_text' => filter_xss($config['message_button_text']),
    ),
  );

  return $block;
}

在.tpl文件中:

   <?php dpm('test'); //<- This works ?>
   <?php dpm($config); //<- This does not work?>

   <div class="message">
    <?php print $config['message_text']; ?>
    <?php if (!empty($config['message_link']) && !empty($config['alert_button_text'])): ?>
      <a href="<?php print $config['message_link']; ?>" class="button">
        <?php print $config['message_button_text']; ?>
      </a>
    <?php endif; ?>
  </div>

我可以在.tpl文件上放置一个dpm('test');,它会出现,所以我知道HTML正在渲染。显然,我也尝试过清除缓存。

有人知道我是否错过了让这些数据出现的步骤?

1 个答案:

答案 0 :(得分:1)

我发现我在hook_theme中错过了配置数组初始化:

function message_theme() {
  return [
    'message_block' => [
      'template' => 'templates/message-block',
      'variables' => [
        'config' => NULL, //<- Was missing
      ],
    ],
  ];
}