7

I am working on Drupal 8, trying to get a page template for each vocabulary. I have tried using hook_theme_suggestions_HOOK_alter() to achieve this, but I was not able to do it.

I tried using Devel with kint(), but no debugging information is shown on my screen.

How can I add a template suggestion for a vocabulary?

13

You can suggest a new template file with the following code.

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

Then create the file: page--taxonomy--VOCABULARYNAME.html.twig and customise it as you wish.

3
  • Thanks for the help. Can you please also tell me how do I print the term name in this template? Apr 30 '19 at 1:34
  • 1
    @SaeedAfzal try using {{ name }} Jan 26 at 17:38
  • ℹ️I've got the Taxonomy Term view that comes with Drupal core enabled, therefore Drupal::routeMatch()->getRouteName() is returning view.taxonomy_term.page_1. HTH. Jan 26 at 19:43
1

In Drupal 9, the getVocabularyId() method is deprecated so we use bundle() instead.

Use this hook in Drupal 9:

use Drupal\taxonomy\Entity\Term;

/*
 * Implements hook_theme_suggestions_HOOK_alter()
 */

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

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.