Create a custom template file for a custom block in drupal

12,364

Solution 1

this seems to work fine.

//implementation of hook_block_info
function mymodule_block_info() {
  $blocks = array();
  $blocks['myblock'] = array(
    'info' => t('My Block Title'),
  );

  return $blocks;
}

//implementation of hook_block_view
function mymodule_block_view($delta='') {
  $block = array();

  switch($delta) {
    case 'myblock' :
      $variables = array(); //do stuff here
      $block['content'] = theme('mytemplate', $variables);
      break;
  }
  return $block;
}


//implementation of hook_theme
function mymodule_theme() {
  return array(
    'mytemplate' => array(
      'variables' => array(),
      'template' => 'mytemplate',
    ),
  );
}

Solution 2

It follows the following suggestion: block_MODULE_DELTA. Following your example above, I'd try naming the file block--mymodule.tpl.php if you have only one block, or block--mymodule--1.tpl.php if you have more than one.

References: api.drupal.org and drupal.org.

Share:
12,364
Nikos Tsagkas
Author by

Nikos Tsagkas

Updated on June 04, 2022

Comments

  • Nikos Tsagkas
    Nikos Tsagkas almost 2 years

    What is the drupal way to create a custom .tpl file for theming a custom block? Specifically I m trying to create a block programmatically and then find a way to separate the view code from the module php code. If it was a page the Drupal theme() would be very efficient way to achieve this. However I can't find what is the Drupal way to do the same thing for custom blocks. I 've tried to use the hook_theme() with no luck.

        //implementation of hook_block_info
        function mymodule_block_info() {
          $blocks = array();
          $blocks['myblock'] = array(
            'info' => t('My Block Title'),
          );
    
          return $blocks;
        }
    
        //implementation of hook_block_view
        function mymodule_block_view($delta='') {
          $block = array();
    
          switch($delta) {
            case 'myblock' :
              $block['content'] = mymodule_get_block_view();
              break;
          }
          return $block;
        }
    
        function mymodule_get_block_view(){
            $variables=array();
            return theme('mytemplate', $variables);
    
        }
    
        //implementation of hook_theme
        function codefactory_theme() {
          return array(
            'mytemplate' => array(
              'variables' => array(),
              'template' => 'mytemplate',
            ),
          );
        }