18

If I want to show the current node title in page.html.twig (by default it seems to only be available in node.html.twig) I have to create a preprocess function like so:

function theme_preprocess_page(&$variables, $hook) {
  // Set our page title so we can access it in page.html.twig
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $variables['my_node_title'] = $node->title->value;
  }
}

And then I have to overwrite page-title.html.twig by copying it into my current theme folder and commenting out everything.

This doesn't seem "right". Is there a better way?

0

3 Answers 3

27

The node is already available in the page template thanks to template_preprocess_page, so there's no need for the preprocess function. You can output the title with:

{{ node.label }}

The page title itself is a block, so if you don't need it any more just remove it from the region at /admin/structure/block. No need to copy the template to your theme or alter the original.

6
  • This doesn't seem to work on the front page, where node is just NULL. Is there a way to get any page title, including the front page title (even when a title override is used)? Commented Mar 4, 2016 at 14:32
  • That's correct @FlorianBrucker - unless the front page is a node, you wouldn't have a node variable available. The title is probably in page['#title'], I'm not sure if that would contain any override made by VIews (but probably)
    – Clive
    Commented Mar 4, 2016 at 14:40
  • @Clive Unfortunately, page['#title'] is an empty string in page.html.twig over here. Commented Mar 4, 2016 at 14:44
  • Pity, I think that was valid at some point in the past, obviously not now. This similar question might help
    – Clive
    Commented Mar 4, 2016 at 14:50
  • @Clive, thanks for the pointer but that didn't help me, either. I've posted a question regarding the issue. Commented Mar 7, 2016 at 9:21
3

You can add below codes to top of node.html.twig in templates folder of your theme :

{% if not page %}
  <h2{{ title_attributes }}>
    <a href="{{ url }}" rel="bookmark">{{ label }}</a>
  </h2>
{% endif %}

{% if page %}
  <h2{{ title_attributes }}>
    {{ label }}
  </h2>
{% endif %}
2

The Drupal 8 code for doing what the code you shown should do is the following one.

function theme_preprocess_page(&$variables) {
  $request = \Drupal::request();
  $route_match = \Drupal::routeMatch();
  if ($route_match->getParameter('node')) {
    $page_title = \Drupal::service('title_resolver')->getTitle($request, $route_match->getRouteObject());
    $variables['my_node_title'] = $page_title;
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.