Theming Module Output

我们两清 提交于 2019-12-25 02:15:43

问题


What I am trying to do is generate some raw output within a module.

I would like to pass an array of data through to a template file, and then use that data to populate the code from the template. The template is represented by a file in my theme folder.

I have a hook set up for a certain URL (/itunes):

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

..inside 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;
}

Here is the hook_theme():

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

Inside my theme's template.php:

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

Right now, $promo_data is being passed through fine, and it is print_r'd on to the result page. However, I'd like to then take this $promo_data variable and use it in my itunes_page.tpl.php template file.

I'm kind of certain I'm close here. Am I supposed to call some sort of render function and pass the $promo_data variable to it from function itunespromo_theme()?


回答1:


I believe you just need to update your hook_theme() to provide the ability to send variables to your template file.

Something like this should do the trick:

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

Also, instead of calling the theme() function directly what you want to be doing is actually constructing a renderable array and letting Drupal call the theme() function. What you should be doing is calling drupal_render which in turn calls theme() for you. Look at this piece of advice here for a little more clarity:

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

In your case you would change your function itunespromo_buildpage to look something like this:

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


来源:https://stackoverflow.com/questions/8392049/theming-module-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!