2011-03-15 32 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) 
}