1

I need to define a block--custom.tpl.php file in a custom module and have that override the theme block.tpl.php.

Here is where I have ended up and it's not working.

Tell Drupal to look in my module:

function MODULE_theme_registry_alter(&$theme_registry) {
  $theme_registry['block']['theme paths'][] = drupal_get_path('module', 'MODULE');
  $theme_registry['block']['theme paths'][] = drupal_get_path('module', 'MODULE') . '/theme';
}

In hook_preprocess_HOOK() suggest a new theme file:

function MODULE_preprocess_block(&$variables) {
  $block = $variables['block'];

  if ($block->CONDITION) {
    $variables['theme_hook_suggestions'][] = 'block__MODULE';
  }
}

Now, I've created the file in the module's theme/ folder and called it block--MODULE.tpl.php.

I've turned on theme debugging in the settings file by un-commenting out $conf['theme_debug'] = TRUE;

Caches have been cleared multiple times. When I load the page I see in the debug comments:

<!-- THEME DEBUG -->
<!-- CALL: theme('block') -->
<!-- FILE NAME SUGGESTIONS:
   * block--MODULE.tpl.php
   * block--block--6.tpl.php
   * block--block.tpl.php
   * block--content.tpl.php
   x block.tpl.php
-->
<!-- BEGIN OUTPUT from 'sites/all/themes/THEME/templates/block.tpl.php' -->

And as you can see from the debug it is using the theme template file.

How do I get Drupal to select the proper theme file?

4
  • There are two different ways to do it suggested here => drupal.org/node/715160, the first one applies to your case. Jun 2, 2016 at 18:52
  • These all talk about nodes and as you can tell from my example, I am using this method (sort of). I need a block specific method. Jun 2, 2016 at 18:53
  • I also don't want to override the block theme registry for all blocks, only those that meet a specific condition. Jun 2, 2016 at 18:56
  • Right you are :-) Let me have a deeper look Jun 2, 2016 at 18:59

1 Answer 1

2

The following worked for me:

/**
 * Implements hook_theme().
 */
function rals_theme($existing, $type, $theme, $path) {
  $theme = array();
  $theme['block__custom'] = array(
    'render element' => 'content',
    'template' => 'block--custom',
    'path' => drupal_get_path('module', 'rals'),
   );
  return $theme;
}


/**
 * Implements hook_preprocess_HOOK().
 */
function rals_preprocess_block(&$variables) {
  $block = $variables['block'];
  if ($block->bid == 3) {
    $variables['theme_hook_suggestions'][] = 'block__custom';
  }
}

and succesfully uses my module-folder-located template file for rendering the block with bid == 3.

Good luck in any case!

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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