1

For theming purpose, I would like to add in body class the vocabulary name (or ID) of the current taxonomy. I know how to add a class based on the taxonomy term ID.

For example, I have the following vocabulary (Color).

  • red (term id = 1)
  • green (term id = 2)
  • yellow (term id = 3)

I know how to get <body class="term-id-1">. I would like to get <body class="vocabulary-id-1"> or <body class="vocabulary-name-color">.

I've tried the following code.

function mytheme_preprocess_html(&$variables) {
  // Works
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical') {
    $variables['term_id'] = \Drupal::routeMatch()->getRawParameter('taxonomy_term');
  }
  // doesn't work
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_vocabulary.canonical') {
    $variables['vocabulary_id'] = \Drupal::routeMatch()->getRawParameter('taxonomy_vocabulary');
  }
}

As said in the comments, it doesn't work, and I am not able to use the vocabulary name, or its ID as CSS class to add to the <body> tag.

How can I achieve this?

3

The vocabulary id is not a route parameter, unless you have a route to view/edit a vocabulary, but these are all admin routes. So you need to get the information from the term:

function mytheme_preprocess_html(&$variables) {
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical') {
    // load the term entity and get the data from there
    $term = \Drupal::routeMatch()->getParameter('taxonomy_term');
    $variables['term_id'] = $term->id();
    $variables['vocabulary_id'] = $term->bundle();
  }
}

bundle() returns the vocabulary of the term. This is the same as a content type of a node. Or a block type of a custom block. All are fieldable bundles of entities.

So if you use bundle() on a node you'll get for example the machine name article.

  • Thanks, it works very well. I understand your explanation. – Sébastien Gicquel Dec 29 '17 at 0:28
  • 1
    +1. I would also point out that in Drupal 8 the ID is the machine name, so vocabulary ID and vocabulary name are the same thing. – kiamlaluno Dec 29 '17 at 8:40
  • @kiamlaluno, I've added an explanation what bundle() does. – 4k4 Dec 29 '17 at 9:52
  • I've put the above code in my .theme file and then went to my views-view.html.twig file and tried to print {{ term_id }} and {{ vocabulary_id }} and both return as null. I'm trying to add the term as a class to the surrounding div so that I can style the different taxonomy term pages. Any ideas as to why I'm not getting any value returned? – ACanadianCoder Mar 16 '18 at 14:28

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.