0

I'd like to add a taxonomy term to the list of CSS classes for a div with the id "primary" on a modified Bartik theme. I know the change needs to happen at page.html.twig or something derived from that, but I'm having a hard time determining how the preprocess page and the twig function together.

Based on this example: How do I theme a taxonomy term page?

I've added the following information to a theme file:

use Drupal\taxonomy\Entity\Term;

function MYTHEME_theme_suggestions_page_alter(&$suggestions, &$vars) {
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical'$
    $term = Term::load($tid);
    $suggestions[] = 'page__taxonomy__' . $term->getVocabularyId();
  }
}

And added a new twig called page--taxonomy--TAXONOMYTERM.html.twig where I added "taxonomy-TAXONOMYTERM" as a class to the div I'm looking to alter:

 <div id="primary" class="{{'taxonomy-TAXONOMYTERM ' ~ 'content-area col-sm-' ~ primary_col }}">

As far as I can tell, according to the example this should work. But in reality, the term isn't showing up when I look at an article with the appropirate taxonomy term. What am I doing wrong? Is there a better way to attach the taxonomy term to a div class?

Thanks!

  • Where does this div live? – Kevin May 3 '18 at 19:18
  • Also I don't think you need to make an entirely new page twig template for this - just create the class in a preprocess and pass it along. It used to be called body_classes but im not sure what it is called now at the moment. – Kevin May 3 '18 at 19:22
  • It lives on both pages and articles -- basically anything that is processed through page.html.twig. – medievalmatt May 3 '18 at 19:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.