Add new template suggestions in your Drupal 7 theme with ease

Fredrik Johansson
Drupal stories
Published in
2 min readFeb 15, 2016

--

In my last Drupal post I wrote about preprocess functions. Here’s another one on the same subject. One common task in preprocessing is adding template (theme hook) suggestions. In my current Drupal 7 project at Cerpus, I created a utility function to make things simpler and my template.php file shorter and cleaner.

The function is called utils_add_theme_hook_suggestions. It duplicates all the current template suggestions in $variables and adds a string that you specify, separated by “__” (two underscores).

Here’s an example where I add suggestions to block templates based on what region they’re in:

function MYTHEME_preprocess_block(&$variables) {
$block = $variables['block'];
// Add region name to all hook suggestions
if($block->region) {
utils_add_theme_hook_suggestions(
$variables,
'region_' . $block->region
);
}
// Run exisiting preprocess functions
// for each of the theme hooks (original and suggested):
utils_preprocess_all_hooks($variables, __FUNCTION__);
}

Before utils_add_theme_hook_suggestions we’d have hooks like this:

block__header
block__menu
block__menu__main_menu

And afterwards we’ll have:

block__header
block__menu
block__menu__main_menu
block__header__region_header
block__menu__region_header
block__menu__main_menu__region_header

So now I can create block — menu — main-menu — region-header.tpl.php and create special markup for my main menu, only when it’s inside the “header” region. Of course there is already a suggestion with the region name in it (block__header), but it’s very generic and sometimes you need something more specific. Also the block__header__region_header suggestion doesn’t add much value, but doesn’t hurt us either. It’s a trivial example, but it gets handy when you want to mix node field values, display modes, etc into your template suggestions.

Here is the actual function that i created for this if you want to try it out:

function utils_add_theme_hook_suggestions(&$variables, $suffix) {
if(empty($variables['theme_hook_suggestions'])) {
$variables['theme_hook_suggestions'] = array();
}
if(!empty($variables['theme_hook_original'])) {
array_unshift(
$variables['theme_hook_suggestions'],
$variables['theme_hook_original']
);
}
$variables['theme_hook_suggestions'] = array_merge(
$variables['theme_hook_suggestions'],
array_map(function($hook) use($suffix) {
return $hook . '__' . $suffix;
}, $variables['theme_hook_suggestions'])
);
}

If you like it, go ahead and use it. If you have feedback, I’m happy to hear it, so please share your thoughts!

--

--