Using custom template file in your drupal module

20 06 2009

Recently we released Accordion blocks module in drupal. This module should work with all standard drupal modules, otherwise this module is not useful. So to make it work with all themes, I decided to use my custom block.tpl.php which is there in my module. But by default drupal will load block.tpl.php from your theme. If there is not block.tpl.php in the theme then it will load block.tpl.php from the block module.

I used hook_theme_registry_alter() hook to load block.tpl.php from my module. I wrote my hook like this.

function example_module_theme_registry_alter(&$theme_registry) {
// using our own block.tpl.php file.
$theme_registry['block']['template'] = 'block';
$theme_registry['block']['path'] = drupal_get_path('module', 'example_module');
$theme_registry['block']['type'] = 'module';
$theme_registry['block']['theme path'] = drupal_get_path('module', 'example_module');
$theme_registry['block']['theme paths'] = Array();
}

Now after enabling my module every time block.tpl.php from my module is loading. This way we no need to alter any template file in the theme folder. This method only works for drupal6-7

update1: We can over write the theme function also. To over write theme function write theme registry alter hook like this.

function example_module_theme_registry_alter(&$theme_registry) {
// using our own block.tpl.php file.
$theme_registry['block']['function'] = 'theme_custblock'; // your custom theme function name
$theme_registry['block']['path'] = drupal_get_path('module', 'example_module');
$theme_registry['block']['type'] = 'module';
$theme_registry['block']['theme path'] = drupal_get_path('module', 'example_module');
$theme_registry['block']['theme paths'] = Array();
}


Actions

Information

7 responses

22 01 2010
Sina Salek

Thanks for sharing , i was trying to do something similar.

4 03 2010
Jordan

Thanks so much for the block. I am using it as navigation and was wondering how you would keep the selected block open when a link is clicked? Any help would be appreciated.

4 03 2010
Prajwala

You are asking about accordion blocks module right?

2 04 2010
Jordan

Yes, I am asking about this module. I am wondering how you keep the active block selected on page refresh. Thanks again.

13 09 2010
Ain

The above code seems to override the default block.tpl.php. The module-specific template appears for all blocks!

2 02 2011
Eugen

same problem, my template file overrides the templates for ALL blocks!

2 02 2011
Prajwala

If you want to have different theme for a single block or some set of blocks, you can use the blocktheme module, skinr module or you can use drupal block template suggestions

Leave a reply to Prajwala Cancel reply