Drupal 7 - 如何从模块加载模板文件?

Moo*_*oon 11 drupal drupal-theming

我正在尝试在Drupal 7中构建自己的模块.

所以我创建了一个名为'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';

}
Run Code Online (Sandbox Code Playgroud)

在moon_page()函数中,我喜欢从我的主题文件加载自定义模板'moon.tpl.php'.

这可能吗?

dob*_*man 15

/*
 * 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
}
Run Code Online (Sandbox Code Playgroud)

  • 'path'在drupal7中运行良好,但是当用'path'调用时,文件应该被称为'theme/moon',没有任何扩展名.如果您使用'template',drupal7会搜索'theme/moon.tpl.php'. (2认同)

Ber*_*dir 10

对于你自己的东西(不覆盖另一个模块的模板)?

当然,你只需要:

  • 使用hook_theme()注册您的模板

  • 调用主题('月亮',$ args)

$ args是一个数组,包含hook_theme()实现指定的模板参数.