Is it possible preprocess variables only for certain blocks?
I created mytheme_preprocess_block__aggregator(&$vars)
, but it doesn't work.
-
The edit you did and the link you pasted there seems to only deal with theme hook suggestions, doesn't it?– leymannxNov 17, 2016 at 20:56
2 Answers
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
}
}
-
4I looked at Drupal code, and Drupal doesn't looks for
hook_preprocess_block_MODULE()
orTHEME_preprocess_block_MODULE()
. It handle in a particular way the__
contained in theme function names, whentheme()
is invoked astheme('links__contextual__node', ...)
, for example.– apaderno ♦Apr 7, 2011 at 15:37 -
-
-
2Please make use of
$variables['block']->bid
and not$variables['block_id']
as 'block_id' is not unique to that block. Sep 5, 2013 at 9:42 -
3I think its a little friendlier to conditionally switch on
$variables['block']->delta
if$variables['block']->module == 'MODULE'
– PeteMay 16, 2014 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 doesMYTHEME_preprocess_block__page_title_block(&$variables)
.– leymannxNov 15, 2016 at 12:24 -
3
mytheme_preprocess_block__{my_block_machine_name}(&$variables)
does work on D8.3– TimMar 17, 2017 at 16:43