Drupal 7 - How to load a template file from a module?
Solution 1
For your own stuff (not overriding a template from another module)?
Sure, you only need to:
Register your template with hook_theme()
Call theme('moon', $args)
$args is an array that contains the arguments to the template as specified by your hook_theme() implementation.
Solution 2
/*
* 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
return theme('moon', $content); // use $content variable in moon.tpl.php template
}
Solution 3
For Drupal 7, it did not worked for me. I replaced line in hook_theme
'file' => 'moon', by 'template' => 'moon'
and now it is working for me.
Solution 4
In drupal 7 I was getting the following error when using :
return theme('moon', $content);
Was resulting in "Fatal error: Unsupported operand types in drupal_install\includes\theme.inc on line 1071"
This was fixed using :
theme('moon', array('content' => $content));
Related videos on Youtube
Moon
Updated on June 09, 2020Comments
-
Moon almost 4 years
I am trying to build my own module in Drupal 7.
So I have created a simple module called 'moon'
function moon_menu() { $items = array(); $items['moon'] = array( 'title' => '', 'description' => t('Detalle de un Programa'), 'page callback' => 'moon_page', 'access arguments' => array('access content'), 'type' => MENU_CALLBACK ); return $items; } function moon_page(){ $id = 3; $content = 'aa'; }
in moon_page() function, I like to load a custom template 'moon.tpl.php' from my theme file.
is this possible?
-
Moon about 13 years// I just put print theme('moon',$content), but it displays a blank page. Am I doing something wrong here?
-
Berdir about 13 yearsIf you print something inside your page callback, it means "I do want only this to be printed. Example: A file, json, xml, ...". Use "return theme('moon', $args)" instead. Did you update the theme registry (re-save theme selection form or use devel.module).
-
Muneer over 12 yearsthankx, this helped me. But need some modification. in return array of moon_theme() funciton the array key 'file' should be repalced with 'template' otherwise it produce error in Drupal 6
-
commonpike almost 11 years'path' worked fine in drupal7, but when called with 'path', the file should literally be called 'theme/moon', without any extensions. if you use 'template', drupal7 searches for 'theme/moon.tpl.php'.