1

Goal: To create a custom fieldable block as available out of the box in D8, which also shows the page title of a a views page, if the page it is displayed on is a views page.

I created a custom block type, and added an image field for the block background.

I then copied and modified the block template to include:

{% if title %}
  <h1>{{ title }}</h1>
{% endif %}

But the views title does not show up. The page source shows nothing rendered. I enable theme debugging and the new block template is being used.

1

Views sets the title configured in a Views page statically in the route definition. Get this title from the current route in a preprocess hook for your specific block content UUID. Add a routecache context, so that the block changes the title when you visit different pages:

function mytheme_preprocess_block(&$variables) {
  if ($variables['plugin_id'] == 'block_content:12345678-1234-5678-90ab-1234567890ab') {
    $variables['title'] = \Drupal::routeMatch()->getRouteObject()->getDefault('_title');
    $variables['#cache']['contexts'][] = 'route';
  }
}
  • Thank you! The plugin_id is something different from the block machine name, right? Where can I find the plugin_id ? – Yuri Apr 1 at 17:37
  • You've said you want to use a custom (fieldable) block. Then the plugin id is composed like in the example, you only need to find the UUID (the longer version of the block content id), for example with the help of Twig Debug or install the Devel module and click on the tab Devel when editing the block. – 4k4 Apr 1 at 17:44
  • 1
    When you place the block in the block layout the UUID is also visible in the url of the button "Place block". – 4k4 Apr 1 at 17:51

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.