0

I would like to pass variables to twig that depend on certain routes or node types (bundles) (a user page, a comment, a page or a custom content type). I used the name of the route (entity.comment.edit_form, entity.user.canonical) for that purpose.

Now I need to exclude some node types (i.e. I can't use just entity.node.canonical for all cases, I need to create a special condition for certain types of nodes). How do I get node type (bundle?) by route name/object?

My code is in the .theme file in HOOK_preprocess_page(&$variables)

UPD: Okay, I have discovered that there is actually $variables['node'] which contains what I need in $variables['node']->getType()

But let's say I have just the route, how do I get an ID from it and load a node?

1 Answer 1

1

Drupal is providing such a variable for the html template:

/**
 * Implements hook_preprocess_HOOK() for HTML document templates.
 */
function node_preprocess_html(&$variables) {
  // If on an individual node page or node preview page, add the node type to
  // the body classes.
  if (($node = \Drupal::routeMatch()->getParameter('node')) || ($node = \Drupal::routeMatch()->getParameter('node_preview'))) {
    if ($node instanceof NodeInterface) {
      $variables['node_type'] = $node->getType();
    }
  }
}

This code works in your HOOK_preprocess_page(&$variables) as well.

UPD: getParameter('node') gets already a loaded node. So you don't need to get the ID to load the node, but if you need the ID then use getRawParameter('node').

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.