0

Adding a dump 'dd()' to parent html.html.twig template file when rendering a 'page type' page I get, among others, the following pair: "node_type" => "page" that I can render within this very template file. When rendering an 'article type' page I get "node_type" => "article". So far so good.

Now I'd need to make use of that variable (node_type) in child template page-title.html.twig. Same dump function retrieves some other variable-value pairs but not the node_type one. I guess they're 'local variables' that are not available out of their own scope. However there may be some way to pass it from parent template but I couldn't find a straightforward simple solution to it. Any clue?

I'm using latest Drupal 9 stable release, so Twig 2 is in charge of theming.

T.I.A.

1 Answer 1

0

You can't pass variables between the two templates as such, but you can make node_type available in page-title.html.twig by copying the code from node_preprocess_html, which is responsible for getting it into html.html.twig in the first place:

function MODULEorTHEME_preprocess_page_title(&$variables) {
  if (($node = \Drupal::routeMatch()->getParameter('node')) || ($node = \Drupal::routeMatch()->getParameter('node_preview'))) {
    if ($node instanceof NodeInterface) {
      $variables['node_type'] = $node->getType();
    }
  }
}
2
  • Ty! I'll give it a try. It seems a clean short way to 'pass' the variable to the template.
    – hip
    Jul 27, 2022 at 22:27
  • Not working. :-( Variable still not appearing child template page-title.html.twig. I wonder whether it may have relation to my theme name having capital letters in its name ('MY_subtheme') as it gave me problems before. drupal.org/project/drupal/issues/3293623
    – hip
    Jul 30, 2022 at 20:55

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.