Score:0

How do I get the bundle name by route?

us flag

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?

Score:1
cn flag

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').

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.