Drupal 7 - How to load a template file from a module?

Moon picture Moon · Mar 14, 2011 · Viewed 23.4k times · Source

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?

Answer

dobeerman picture dobeerman · Mar 15, 2011
/*
 * 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
}