Drupal:将自定义模块中的自定义变量传递给我的模板

时间:2011-10-07 03:01:59

标签: drupal drupal-6 preprocessor drupal-modules customization

我意识到这个问题已被提出,但我要么根本不理解,要么以前的答案不适用(或者我不明白如何应用它们)到我的情况。这是:

我有一个名为的自定义模块:

/ sites / all / modules / custom / my_module

中的“my_module”

我有一个模块文件:

/sites/all/modules/custom/my_module/my_module.module

我有一个页面模板名称“page-mypage”,它不在我的模块中:

/网站/所有/主题/ 的MyTheme /网页 /page-mypath-mypage.tpl.php

我为此制作了钩子菜单:

$items['mypath/mypage'] = array(
    'title'         => 'My Page!',
    'page callback'         => 'my_module_mypage',
    'page arguments'    => array(1,2),
    'access callback'   => true,
    'type'          => MENU_CALLBACK,
);

在这个函数中,我建立了一些像这样的内容:

function my_module_mypage($x, $y) {
    $output = "foo AND bar!";
    return $output;
}

在模板中(同样,不是在我的模块文件夹中,而是在THEME子文件夹“页面”中,我有:

<?php print $content ?>

当我去http://mysite/mypath/mypage时,我得到了“foo AND bar!”

现在提出问题。我想要一个在my_module_mypage()中定义的新变量,名为'$ moar_content'。我想在我的page-mypath-mypage.tpl.php中输出$ moar_content。我只需要为此模块和此模板执行此操作。我不需要它在主题范围内,所以我不认为使用mytheme的'template.php'是合适的。

我想我需要使用某种预处理,但我尝试的一切都失败了,我读到的所有内容似乎都缺少某种神奇的成分。

我的想法是:

function my_module_preprocess_page_mypath_mypage(&$variables) {
    $variables['moar_content'] = 'OATMEAL';
}

function my_module_preprocess_my_module_mypage(&$variables) {
    $variables['moar_content'] = 'OATMEAL';
}

或者其他什么。我很确定我在正确的轨道上,但我正在撞墙。

1 个答案:

答案 0 :(得分:1)

要完成这项工作,您必须遵循Drupal的最佳实践,假设您使用的是D6,因此您可以将一些变量插入模板,如下所示:

// You menu path is good
$items['mypath/mypage'] = array(
    'title' => 'My Page!',
    'page callback' => 'my_module_mypage',
    'page arguments' => array(1,2),
    'access callback' => true,
    'type' => MENU_CALLBACK,
);

第二件事,我们为页面定义主题钩子

// We define here a new theme file for your your page
// Your theme file must be located in your module's folder
// you can use a subfolder to group all your module's theme files
// E.g : themes/my-module-theme.tpl.php
// Note that in theme files, we change _ by -
function my_module_theme() {
    return array(
        'my_module_theme' => array( // Keep that name in your mind
            'template' => 'my_module_theme',
                'arguments' => array(
                'my_var' => NULL,
                'my_var2' => NULL,
            ),
        )
    );
}

现在我们可以在模块的根文件夹中创建一个文件“my-module-theme.tpl.php”,并粘贴类似“foo AND bar!”的内容。 回到我们的my_module.module,回调必须是:

function my_module_mypage($x, $y) {
    // $x and $y are optionnal, so this is the first manner
    // to inject variables into your theme's file
    $output = theme("my_module_theme", $x, $y);
    return $output;
}

您也可以使用预处理挂钩来插入变量

// The hook must be named like this : template_preprocess_NAME_OF_THEME_FILE
// where NAME_OF_THEME_FILE is the name that you kept in your mind ;)
function template_preprocess_my_module_theme(&$variables) {
    // Do some job
    $var1 = 'Foobar';

    // So in "my-module-theme.tpl.php", $my_var1 will print Foobar
    $variables['my_var1'] = $var1;
}
相关问题