Theming Module Output

2019-08-29 03:15发布

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条回答
贼婆χ
2楼-- · 2019-08-29 04:06

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;
}
查看更多
登录 后发表回答