Drupal Tutorial - How to Override a Block Templates from a Custom Module

When I was creating a new module called Responsive Menu Combined, I wanted to find a solution for overriding the block templates. This is very easy to do when you are trying to do this inside your theme. The solution to do it inside a module is not as straightforward. I could not find any documentation on Drupal.org on this subject. Inside your themes folder all you have to do is:

  1. copy the /modules/block/block.tpl.php file into your MYTHEME/templates folder
  2. rename block.tpl.php to block--MYCUSTOMMODULE.tpl.php

This is more difficult when you are "Theming" things inside a module. Luckily, I came across a solution for overriding a views template file, and applied it to my block. http://grayside.org/2010/09/how-override-views-field-template-module.

Here is what I did:

<?php
/**
* Implements hook_theme().
*/
function responsive_menu_combined_theme($existing, $type, $theme, $path) {
  // Custom template for that overrides the default block.tpl.php.
  $themes['block__responsive_menu_combined'] = array(
    'template' =--> 'block--responsive-menu-combined',
    'original hook' => 'block',
    'path' => drupal_get_path('module', 'responsive_menu_combined') . '/templates',
  );
  return $themes;
}

Inside my modules template folder, I have block--responsive-menu-combined.tpl.php By adding the block template to the theme registry, you are doing the equivalent of building your template and dropping it into your Theme’s directory. After adding the code then clearing your cache, Drupal will now notice the existence of the template from within your module and use its own logic to finding the most specific template available for each block. For more information about Drupal logic, check out Drupal 7 Template (Theme Hook) Suggestions.

Note: The name of the theme key and template are the same, however, hyphens and underscores are swapped. The way you named yours is critical. If they are not the same, then Drupal's system will not index the block templates.

Add new comment

Filtered HTML

  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.