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 How can I dynamically add URL or taxonomy to body class to work out a solution, but it seems 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 module.

1 Answer 1


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:


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


  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
    Commented Aug 16, 2017 at 10:14

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.