2

I have a block object in drupal 8 that I am trying to get the title of. I tried $block->label() and it seems to work for some block types, but not for Views blocks. On those, it returns the block's admin label, not the configured title.

If it matters, I am trying to find this information from hook_preprocess_region().

1

If you were using hook_preprocess_block() it would be much easier to get the title, you would simply load the block by its id and get the label from the returned block object like this:

function hook_preprocess_block(&$variables) {
  $variables['new_title'] = \Drupal\block\Entity\Block::load($variables['elements']['#id'])->label();
}
  • Like I mentioned in the question, the trouble is that the method $block->label() doesn't return the proper title when used with views blocks. Also, I do have the block object of interest loaded in my hook_preprocess_region(), and can do whatever is necessary with it. – computer-whisperer Aug 24 '15 at 12:17
0

The label of the block entity is the admin label. It might or might not be used as the label that is actually printed out.

First, there is a setting that allows to control if a label should be printed or not. Second, block plugins can return a label from their build() method that will override the one used in the UI. See the code in template_preprocess_block() for reference:

  $variables['label'] = !empty($variables['configuration']['label_display']) ? $variables['configuration']['label'] : '';
  // A block's label is configuration: it is static. Allow dynamic labels to be
  // set in the render array.
  if (isset($variables['elements']['content']['#title']) && !empty($variables['configuration']['label_display'])) {
    $variables['label'] = $variables['elements']['content']['#title'];
  }

That said, I don't think you can access that in the region preprocess however, because the blocks haven't been built yet and their output might be cached, so the block preprocess will never be called in that case.

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.