How to implement hook_theme in drupal 7?

15,790

Try to add the variables array in hook_theme

function mytheme_theme($existing, $type, $theme, $path){
    return array(
        'mytheme_header' => array(
            'template' => 'header',
            'path' => $path . '/templates',
            'type' => 'theme',
            'variables' => array(
                'title' => NULL,
                'some_text' => NULL,
            ),
        ),
    );
}

In your header.tpl.php file:

<h1><?php print $title; ?></h1>
<p><?php print $some_text; ?></p>

Then, print it out like this:

$vars = array();
$vars['title'] = "This is a title";
$vars['some_text'] = "Some text...";
print theme('mytheme_header', $vars);
Share:
15,790
solomon_wzs
Author by

solomon_wzs

Updated on June 05, 2022

Comments

  • solomon_wzs
    solomon_wzs almost 2 years

    I created a new drupal 7 theme and trying to implement hook_theme at template.php like this:

    function mytheme_theme($existing, $type, $theme, $path){
        return array(
            'mytheme_header'=>array(
                'template'=>'header',
                'path'=>$path.'/templates',
                'type'=>'theme',
            ),
        );
    }
    

    then I placed header.tpl.php into templates directory and cleared all caches, and call theme function:

    theme('mytheme_header', $vars);
    

    and header.tpl.php likes this:

    <?php
    fb('calling header template');//the function of FirePHP to output debug info
    print '<div>Header</div>';
    //...
    

    I check Firebug and it get the info 'calling header template', it mean it had called header.tpl.php, but it didn't print the html code. What's wrong with my code?

  • Clive
    Clive over 11 years
    arguments was renamed to variables in Drupal 7
  • solomon_wzs
    solomon_wzs over 11 years
    It was not the problem of variables. I debug with FirePHP and I found that It had called header.tpl.php but it didn't print any html code.
  • solomon_wzs
    solomon_wzs over 11 years
    I'm sorry, I called theme($hook, $vars), but I should call print theme($hook, $vars).