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

前端 未结 5 566
时光说笑
时光说笑 2021-02-08 04:06

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         


        
相关标签:
5条回答
  • 2021-02-08 04:29

    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',
        ),
      );
    }
    
    0 讨论(0)
  • 2021-02-08 04:40

    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.

    0 讨论(0)
  • 2021-02-08 04:46

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

    0 讨论(0)
  • 2021-02-08 04:48
    /*
     * 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
    }
    
    0 讨论(0)
  • 2021-02-08 04:56

    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.

    0 讨论(0)
提交回复
热议问题