2

I have a taxonomy vocabulary whose various parents and children need to have different styles. I would need the tid of the every taxonomy page to appear as a class in the body tag in order to make CSS selectors.

I tried using this to work out a solution, but it appears to work only for nodes. I get a class called path-taxonomy for every taxonomy term and that's it.

I would prefer not to install any modules. Thank you

3

The linked example gets the path. Here better use routing. Check the name of the matched route and then get a parameter which is defined in the route. Normally you use getParameter() to get the loaded entity, in this case it's getRawParameter() for the id:

mytheme.theme:

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

html.html.twig:

{%
  set body_classes = [
    term_id ? 'term-id-' ~ term_id,
  ]
%}
<body{{ attributes.addClass(body_classes) }}>
  • Awesome answer, thanks. At first I had huge problems with the changes not wanting to take effect, I spent literally an entire day clearing caches, setting up twig, and the changes appeared only this morning, just as I was thinking there was no more hope for my site. – alouette Aug 16 '17 at 10:14
  • I can't get this to work. Are you sure the code is correct? – Yuri Mar 8 at 15:26

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.