Search code examples
drupal-7drupal-theming

Create a custom template file for a custom block in drupal


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

Solution

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