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

心不动则不痛 提交于 2019-12-03 06:04:38

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.

/*
 * 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
}
user1765355

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.

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));

You may use moon_menu, with hook_theme

<?php

/**
 * Implementation of hook_menu().
 */
function os_menu() {
  $items['vars'] = array(
    'title' => 'desc information',
    'page callback' => '_moon_page',
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

function _moon_page() {    
  $fields = [];
  $fields['vars'] = 'var';

  return theme('os', compact('fields'));
}

/**
 * Implementation of hook_theme().
 */
function os_theme() {
  $module_path = drupal_get_path('module', 'os');

  return array(
    'os' => array(
      'template' => 'os',
      'arguments' => 'fields',
      'path' => $module_path . '/templates',
    ),
  );
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!