How to theme a custom block from a module in Drupal

If you need to include a custom template for a block in your Drupal 7 module, here's how to do it.
First, in your .module file, use hook_theme to register your template.

function hook_theme($existing, $type, $theme, $path) {  
	$themes['block__module__delta'] = array( // replace module--delta with your block template suggestions
	    'variables' => array('block' => array()),   
	    'template' => 'block--module--delta', // the name fo your .tpl.php file.
	    'path' => $path . '/templates',   // path to the template in your module
	  );
 
	return $themes; 
}

For more information on template suggestions and how to target your specific block, check out this documentation.

 

Second, create your block template file. A good starting point is the block.tpl.php file from the block module:

<div id="<?php print $block_html_id; ?>" class="<?php print $classes; ?>"<?php print $attributes; ?>>
 
  <?php print render($title_prefix); ?>
<?php if ($block->subject): ?>
  <h2<?php print $title_attributes; ?>><?php print $block->subject ?></h2>
<?php endif;?>
  <?php print render($title_suffix); ?>
 
  <div class="content"<?php print $content_attributes; ?>>
    <?php print $content ?>
  </div>
</div>

 

And that's all you need to do. Make sure you clear your cache so Drupal detects your theme changes.