Score:1

How can I add term's vocabulary name as body class?

us flag

I already had following codes added, which adds term ID as body class. However, how can I change the ID to term's vocabulary name?

For example:

<body class="term-type-cameras">

/**
 * Implements template_preprocess_html().
 */
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();
    $variables['attributes']['class'][] = 'term-' . $term->id();
  }
}
leymannx avatar
ne flag
The original code looked like you did this in the Claro theme code. I hope that was just a sample and you created your own custom theme or module for that. Never hack core or contrib. Changes will get lost on the next update.
us flag
Thanks @leymannx, I did build my site based on Claro, but it's really my first ever time to know that...Appreciate your reminder! :)
Score:2
mk flag

You can use $term->bundle() method to get term vocabulary and then use it as part of the class.

$variables['attributes']['class'][] = 'term-type-' . $term->bundle();
No Sssweat avatar
ua flag
You should pass the `$term->bundle()` through [cleanCssIdentifier](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Component%21Utility%21Html.php/function/Html%3A%3AcleanCssIdentifier/8.2.x)
I sit in a Tesla and translated this thread with Ai:

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.