0

I'm using drupal 8.

I use the view provided by default: "taxonomy term".

I would like to make a presentation of the page (and not only of the node) different according to the term of taxonomy.

I tried with this code (in .theme) and template suggestion :

use Drupal\taxonomy\Entity\Term;

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

But it does not work because (i think) it is a view.

I tried with the views template suggestion but it works only for the whole page and not for each taxonomy term.

Does anyone have the solution ?

  • It doesn't matter that this is a view, because the view replaces the entity route with the same name and parameter. So your code seems to be OK. What do you expect and what doesn't work? Did you check the Twig debug output? – 4k4 Mar 29 '18 at 9:00
0

You can define each template by using template page--taxonomy--term--xxx.html.twig where xxx is your term id.

In your code, $term->getVocabularyId(); will return machine name of vocabulary, not the term id. It mean all term of this vocabulary will use this template.

0

If you are looking to add suggestions based on the name of each term then you may add as below

use Drupal\taxonomy\Entity\Term;

function THEME_NAME_theme_suggestions_page_alter(&$suggestions, &$vars) {
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical' && $tid = \Drupal::routeMatch()->getRawParameter('taxonomy_term')) {
    $term = Term::load($tid);
    $suggestions[] = 'page__taxonomy__' . $term->getVocabularyId();
    // To add suggestions based on route name
    $suggestions[] = 'page__taxonomy__term__' . strtolower(str_replace(' ', '_', $term->getName()));
  }
}

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.