Is it possible preprocess variables only for certain blocks? I have created such function: mytheme_preprocess_block__aggregator(&$vars) but it doesn't works.

-- EDIT --

It seems to be fixed in Drupal 8 https://drupal.org/node/1751194

  • The edit you did and the link you pasted there seems to only deal with theme hook suggestions, doesn't it? – leymannx Nov 17 '16 at 20:56

Unfortunately, there is no way to do it like that (similar to hook_form_alter()).

The best way to do this would be to use $variables['block']->bid to apply modifications only to the blocks you want:

function mytheme_preprocess_block(&$variables) {
  if ($variables['block']->bid === 'target_block_id') {
    // do something for this block
  } else if ($variables['block']->bid === 'other_target_block_id') {
    // do something else for this other block
  • 4
    I looked at Drupal code, and Drupal doesn't looks for hook_preprocess_block_MODULE() or THEME_preprocess_block_MODULE(). It handle in a particular way the __ contained in theme function names, when theme() is invoked as theme('links__contextual__node', ...), for example. – kiamlaluno Apr 7 '11 at 15:37
  • Hmm, good to know! – Alex Weber Apr 7 '11 at 17:09
  • 'block_id' is usually the machine name of the block correct? – chrisjlee Sep 26 '11 at 14:46
  • 2
    Please make use of $variables['block']->bid and not $variables['block_id'] as 'block_id' is not unique to that block. – Duncanmoo Sep 5 '13 at 9:42
  • 3
    I think its a little friendlier to conditionally switch on $variables['block']->delta if $variables['block']->module == 'MODULE' – Pete May 16 '14 at 0:02

Just to confirm, in Drupal 8 you can write preprocess functions for specific blocks. For example:

Drupal 8

mytheme_preprocess_block__system_branding_block(&$vars) {
  // Make changes to the the system branding block

But you could also use hook_preprocess_block, and the plugin ID:

function mytheme_preprocess_block(&$vars) {
  if ($vars['plugin_id'] == 'system_branding_block') {
    // Make changes to the the system branding block

As mentioned by Alex, in Drupal 7 you'll have to stick with HOOK_preprocess_block, and an id check:

Drupal 7

mytheme_preprocess_block(&$vars) {
  if ($vars['block']->bid === 'target_block_id') {
    // make changes to this block
  • Tried it out right now on D8, neither MYTHEME_preprocess_block__system_branding_block(&$vars) works nor does MYTHEME_preprocess_block__page_title_block(&$variables). – leymannx Nov 15 '16 at 12:24
  • 1
    mytheme_preprocess_block__{my_block_machine_name}(&$variables) does work on D8.3 – Tim Mar 17 '17 at 16:43

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.