Manipulating Drupal blocks with hooks

We have been developing a Drupal module called 'slices' for a while now. This module has a number of requirements, but essentially gives site editors a more jigsaw-like approach to building up a content item.

One of this module's requirements is to add a counter class to show the number of items within a block. While this is a reasonably straightforward objective to achieve, it does require jumping through some hoops.

The block view

For the purpose of this exercise we are using a custom_module and this module is creating the block in code, using block_info and block_view hooks, although I'm pretty sure you could use the same technique with the block_alter hook.

function custom_module_block_view($delta = '') {
    // Some code to render our block and store the number of items (e.g. teasers)       
    $block['content']['#content'] = "Our module content";       
    // We can store additional variables alongside our block
    $block['no_of_items'] = $no_of_items;

    return $block;

The block pre-process

Prior to rendering our block we can use hook_preprocess_block() to amend classes among other items.

function custom_module_preprocess_block(&$vars) {
    if (isset($vars['block']->no_of_items)) {
        $variables['classes_array'][] = 'items-' . $vars['block']->no_of_items;

This means that each of our custom module blocks will now contain a counter class allowing them to be styled to a responsive grid.

Theme suggestions for blocks

We can also add a theme suggestion for our custom module, by simply checking for the block's originating module, and acting accordingly.

 function custom_module_preprocess_block(&$vars) {
    if ($vars['block']->module == 'custom_module') {
        array_unshift($variables['theme_hook_suggestions'], 'block__custommodule');

As we do not want to override any template suggestions for the specific block we use array_unshift to put it to the bottom of the theme suggestion pile.

We can then create a template file


which will be used for all blocks originating from our custom module.