Create a custom template file for a custom block in drupal

Nikos Tsagkas picture Nikos Tsagkas · May 15, 2013 · Viewed 12.2k times · Source

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',
        ),
      );
    }

Answer

davidneedham picture davidneedham · May 26, 2013

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.