Drupal中hook_theme函数用法

本文实例讲述了Drupal中hook_theme函数用法。分享给大家供大家参考。具体如下:

在开发的时候不免要使用到drupal theme 定义。
举个简单的例子:

<?php
function modulename_theme() { //开始定义自己的theme 使用api hook_theme
return array( //返回theme 数组
'hot_news' => array( // 给定义的theme 定义一个名称
'arguments' => array('title' => NULL, 'teaser' => NULL, 'link' => NULL), //这些都是要传递的参数,具体是在使用 theme('hot_news',arg1,arg2,arg3),这时使用到。
'template' => 'hot_news', //模板名称,它会自动搜索hot_news.tpl.php模板文件
'file' => 'get_page.inc', //这个是定义相关函数的文件,根据需要自行定义。
'path' =>drupal_get_path('module', 'modulename'), //得到文件路径,如果theme('hot_news',arg)在template.php里面使用,需要告诉drupal具体位置,不定义,如果在template使用,它只能在template.php同目录下查找。默认和主题同目录。
),
);
?>

每个参数都会写入变量里。 variables.,比如:$variables['title'], $variables['teaser'] and $variables['link'].
接下去就可以使用:

<?php
$output = theme('hot_news', '这是标题','haha,teaser','yes, 这是link');//使用这个时候,他会输出定义的hot_news.tlp.php模板内容样式。、。
?>

还有一个功能就是预处理机制。

<?php
function template_preprocess_hot_news(&$variables) {
// $variables['title'] 的值可以使用 $title 在你的hot_news.tpl.php里面输出
$variables['title'] = '在处理一次,让它显示别的title';
$variables['teaser'] = 'strng......';
$variables['link'] = l(eeeee, 'node/'.1);
}
?>

理解hook_theme,就可以自己随心所欲来定制自己的theme。感觉到drupal的强大和灵活了。

总结:

当告知drupal使用theme('hook',arg)时, 它需要找到hook_theme的定义,如果没有preprocess,那直接把参数送给你tpl.php文件里。如果有,它就把theme('hook',arg)的来参数,传递给preprocess里面,可以直接用$variables['arg']得到值,看看没有重新赋值,如果有,那就使用新的$variables['arg'],最后输出到tpl.php里面。

希望本文所述对大家的drupal建站有所帮助。