6

Is there a way to use a custom template for each block by title? For example, if I named my block "test1", and it is in the region "left1", I want to use the following template suggestions:

  • block-left1-test1.tpl.php
  • block-left1.tpl.php
  • block-test1.tpl.php

Is there a list of template suggestions for blocks?

migrated from stackoverflow.com May 1 '11 at 21:48

This question came from our site for professional and enthusiast programmers.

6

The Drupal theming system has a concept called "template suggestions". When a theme hook is invoked, Drupal checks if the theme hook is implemented as a template or as a function. In case of a template, All preprocess functions for that theme hook are invoked. This means that every module or template can add its own data to the variables that will be made available to the template. Those variables are passed around as a large array, $variables. This array can contain a list of template suggestions as a nested array called $variables['template_files']. Drupal will later reverse that list and use the first existing template it can find. See the documentation on drupal.org for more details.

Now what you can do is:

  1. Add a function to your theme's template.php named [themename]_preprocess_[themehook] (eg. function mytheme_preprocess_block(&$variables) {} )
  2. In that function, construct the desired template name suggestions
  3. Add those suggestions to the $variables['template_files'] array

By the way, if I'm not mistaken you cannot use the region name in the template suggestion, because at the time the block is rendered, it is not yet known in which region the output will be shown.

PS 1: It helps if you tell us which Drupal version you're using.

PS 2: I'm voting for this question to be moved to https://drupal.stackexchange.com/

  • Something like that: function mytheme_preprocess_block(&$vars) { array_unshift($vars['template_files'], 'block-' . $vars['region'] . '-' . filter_xss($vars['subject'])); } – yoavmatchulsky May 1 '11 at 11:29
3

The template suggestion patterns for blocks (and the rest of core) can be found at http://drupal.org/node/1089656. Instead of using the block's title, you use the block's id, such as block--block--1.tpl.php would be for the block that block module defined (user defined) with an id of 1 (you can find the id and module in the url when you edit a block).

You can also use region names, but there's no need to use both the id and the region name since a block can only go into one region.

1

I'm not sure if it would do exactly what you're looking for, but the Block Theme module sounds close. A similar module worth looking into is Skinr.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.