2011-03-15 65 views
0

因此,我创建了一个名为“月亮”的模块。在模块中,我使用moon_menu来分配一个菜单来调用moon_page以向浏览器显示某些内容。Drupal 7 - 如何将变量分配给模板?

function moon_page(){ 

$moonsvariable = 'hi this is a function'; 
return theme('moon_display',$moonsvariable); 

} 

是否可以将自定义变量分配给模板,然后在模板中使用它?

我想通过以下方式。

function moon_page(){ 

    $custom_variable = "this is a custom variable"; 
    $moonsvariable = 'hi this is a function'; 
    return theme('moon_display',$moonsvariable); 

} 

然后我喜欢在我的主题中使用<? print $custom_variable ?>来显示它。我试过variable_set,但它不起作用。

+0

我很困惑。你为什么不把'$ custom_variable'传递给主题函数? – 2011-03-15 02:52:26

+0

@Karl Bielefeldt //然后...我的主题只是输出它。我实际上想分配一个数组然后手动在模板文件中循环它。 – Moon 2011-03-15 03:08:32

回答

3
/* 
* Implementation of hook_theme(). 
*/ 
function moon_theme($existing, $type, $theme, $path){ 
    return array(
    'moon' => array(
     'variables' => array('content' => NULL), 
     'file' => 'moon', // place you file in 'theme' folder of you module folder 
     'path' => drupal_get_path('module', 'moon') .'/theme' 
    ) 
); 
} 

function moon_page(){ 

    // some code to generate $content variable as array 
    $content['data1'] = 'Lorem ipsum'; 
    $content['data2'] = 'Ipsum lorem'; 

    return theme('moon', $content); // use $content variable in moon.tpl.php template 

    // Or you can use few 'variables' in hook_theme function 
    // smth like this 'variables' => array('content1' => NULL, 'content2' => NULL) 
    // and return page as theme('moon', var1, var2) 
}