【问题标题】:How to implement hook_theme in drupal 7?如何在 drupal 7 中实现 hook_theme?
【发布时间】:2012-10-20 05:53:42
【问题描述】:

我创建了一个新的 drupal 7 主题并尝试在 template.php 中实现 hook_theme,如下所示:

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

然后我将header.tpl.php放入templates目录并清除所有缓存,并调用主题函数:

theme('mytheme_header', $vars);

header.tpl.php 喜欢这样:

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

我检查了 Firebug,它得到了“调用标头模板”的信息,这意味着它调用了 header.tpl.php,但它没有打印 html 代码。我的代码有什么问题?

【问题讨论】:

    标签: php drupal drupal-7 drupal-theming


    【解决方案1】:

    尝试在hook_theme中添加variables数组

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

    在您的header.tpl.php 文件中:

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

    然后,像这样打印出来:

    $vars = array();
    $vars['title'] = "This is a title";
    $vars['some_text'] = "Some text...";
    print theme('mytheme_header', $vars);
    

    【讨论】:

    • arguments 在 Drupal 7 中重命名为 variables
    • 不是变量的问题。我用 FirePHP 调试,发现它调用了 header.tpl.php 但它没有打印任何 html 代码。
    • 对不起,我打电话给theme($hook, $vars),但我应该打电话给print theme($hook, $vars)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-05
    相关资源
    最近更新 更多