【问题标题】:Theming Module Output主题模块输出
【发布时间】:2011-12-05 21:22:00
【问题描述】:

我想做的是在模块中生成一些原始输出。

我想将一组数据传递给模板文件,然后使用该数据填充模板中的代码。模板由我的主题文件夹中的一个文件表示。

我为某个 URL (/itunes) 设置了一个挂钩:

$items['itunes'] = array(
    'page callback'     =>  'itunespromo_buildpage',
    'type'              =>  MENU_SUGGESTED_ITEM,
    'access arguments'  =>  array('access content'),
);

..在 itunespromo_buildpage 内...

function itunespromo_buildpage() {
    //grab some data to pass through to template file, put into $promo_data
    $details = theme('itunes_page', array(
        'promo_data'    =>   $promo_data,
    ));
    return $details;
}

这里是 hook_theme():

function itunespromo_theme() {
    return array(
        'itunes_page'   =>  array(
            'template'  =>  'itunes_page',
        ),
    );
}

在我的主题的 template.php 中:

function geddystyle_itunes_page($vars) {
    return print_r($vars['promo_data'], true);
}

现在,$promo_data 被很好地传递,它被 print_r'd 打印到结果页面上。但是,我想在我的 itunes_page.tpl.php 模板文件中使用这个 $promo_data 变量。

我可以肯定我就在附近。我是否应该调用某种渲染函数并将 $promo_data 变量从函数 itunespromo_theme() 传递给它?

【问题讨论】:

  • 您使用的是什么版本的 Drupal?

标签: drupal drupal-modules


【解决方案1】:

我相信您只需要更新您的 hook_theme() 以提供将变量发送到您的模板文件的能力。

这样的事情应该可以解决问题:

function itunespromo_theme($existing, $type, $theme, $path) {
 return array(
  'itunes_page'   =>  array(
    'variables' => array(
      'promo_data' => NULL,
      ),
      'template' => 'itunes_page',
    )
  );
}

另外,您想要做的不是直接调用theme() 函数,而是实际构建一个可渲染数组并让Drupal 调用theme() 函数。你应该做的是调用 drupal_render ,然后它会为你调用 theme() 。看看这里的这条建议会更清楚一点:

http://drupal.org/node/1351674#comment-5288046

在您的情况下,您可以将函数 itunespromo_buildpage 更改为如下所示:

function itunespromo_buildpage() {
  //grab some data to pass through to template file, put into $promo_data
  $output = array(
  '#theme' => 'itunes_page',
  '#promo_data' => $promo_data //call $promo_data from the tpl.php page to access the variable
  );
  $details = drupal_render($output);
  return $details;
}

【讨论】:

  • 哇.. 效果很好。非常感谢,你不知道我今天从头上拔了多少头发。就脱发而言,我基本上已经穿了 30 年。
  • 哎呀,说得很快.. 鉴于这些变化,我如何从 itunes_page.tpl.php 中访问 $promo_data 变量。
  • 鉴于 $promo_data 在 $options 中的代码。 (在 $output 中声明为 #options - 只需将 #options 更改为 #promo_data 即可)我已对其进行了更改以反映您应该做什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-16
  • 1970-01-01
  • 1970-01-01
  • 2012-06-06
  • 2021-02-12
  • 1970-01-01
  • 2019-02-10
相关资源
最近更新 更多