Problem/Motivation
Currently, the custom CSS classes are injected in block's render array at the preprocess level:
https://git.drupalcode.org/project/block_class/-/blob/3.0.0/block_class....
/**
* Implements hook_preprocess_HOOK().
*/
function block_class_preprocess_block(&$variables) {
// Blocks coming from page manager widget does not have id.
if (!empty($variables['elements']['#id'])) {
$block = Block::load($variables['elements']['#id']);
if ($block && $classes = $block->getThirdPartySetting('block_class', 'classes')) {
$classes_array = explode(' ', $classes);
foreach ($classes_array as $class) {
$variables['attributes']['class'][] = Html::cleanCssIdentifier($class, []);
}
}
}
}
Which requires an extra call to Block::load to load the block, to be able to access its CSS classes.
Could the Block entity be accessible at an earlier stage of the rendering flow?
This way maybe the CSS classes could be added to the render array without having to reload the block.
Steps to reproduce
Display any block with Block classes.
Another way is to run PHPUNIT Functional tests.
Proposed resolution
Look in the backtrace of the preprocess function, at earlier stages of the rendering pipeline of a Block entity, for example see:
https://git.drupalcode.org/project/drupal/-/blob/11.3.9/core/modules/blo...
\Drupal\block\BlockViewBuilder::buildPreRenderableBlock()
Maybe we could convert the current implementation with a preprocess:
block_class_preprocess_block
to a hook_block_view_alter:
block_class_block_view_alter
At the BlockViewBuilder level, the block entity object should be already available and the CSS classes could maybe be added to the build render array without having to reload the block.
Remaining tasks
User interface changes
API changes
Data model changes
Issue fork block_class-3590322
Show commands
Start within a Git clone of the project using the version control instructions.
Or, if you do not have SSH keys set up on git.drupalcode.org:
Comments
Comment #4
dydave commentedQuick follow-up on this issue:
Block::loadwas removed.Since all the tests and jobs were still passing 🟢, I went ahead and merged the changes above at #3.
Marking issue as Fixed, for now.
Feel free to let us know if you encounter any issues with this change, we would surely be glad to hear your feedback.
Thanks in advance!