3

This question already has an answer here:

I want to make different page.html.twig according to different Vocabulary. I found this code:

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();
  }
}

in How do I theme a taxonomy term page?. Code does not work:

Fatal error: Class 'Term' not found in...

Excuse me, what is the reason, I really need to customize the page.html.twig according to the vocabulary, you can help me?

marked as duplicate by Shawn Conn, DRUPWAY, Pierre.Vriens, kiamlaluno Oct 17 '16 at 7:00

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1

Because you have not included the PHP code that contains the Class.

See Namespacing in PHP.

According to term.php the name space is Drupal\taxonomy\Entity.

So you need to add use [name space]\[class name]; at the top.

Therefore, it would be use Drupal\taxonomy\Entity\Term;.

Example:

<?php

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();
  }
}
  • Thank you very much for your answer, you are a good person, but still do not understand, can not directly code, thank you very much! – LIUJIAHUI Oct 16 '16 at 4:48
  • @LIUJIAHUI Did you get it to work? If not working, did you get any errors? or ??? – No Sssweat Oct 16 '16 at 5:02
  • 1
    No Sssweat,The problem is solved, thank you very much! – LIUJIAHUI Oct 16 '16 at 5:10
  • Very sorry, I was the first time to submit a question, I do not know where to choose... – LIUJIAHUI Oct 16 '16 at 5:53
  • Don't sweat it, welcome to Drupal Answers :) – No Sssweat Oct 16 '16 at 6:07

Not the answer you're looking for? Browse other questions tagged or ask your own question.