I'm new to Drupal and I don't have extensive knowledge so I'm hoping I can get this question answered. I want the taxonomy pages of lower hierarchy to be displayed differently from the higher by applying a different tmeplate. Is there a way in Drupal 8 to do this other than giving each term its own template?


What template exactly? taxonomy-term.html.twig, I guess?

You're looking for template suggestions. See Working with template suggestions on Drupal 8 for a similar question.

You can implement hook_template_suggestions_TEMPLATE() and then provide alternative file names for whatever condition you can think of.

  • Thanks for your answer. But is there a way to get the hierarchy or weight of the term inside the hook function? Like it is possible to get the request parameter with with \Drupal::request()->query->get('foo') ? – Dorian Mar 24 '15 at 14:25

Thanks to @Berdir 's answer I was able to come up with this hook, which does it for me.

function MYTHEME_theme_suggestions_page_alter(array &$suggestions, array $variables) {
   $tid = \Drupal::routeMatch()->getRawParameter('taxonomy_term');
   $weight = \Drupal::entityManager()->getStorage('taxonomy_term')->load($tid)->getWeight();
   if ($weight == 0) {
      $suggestions[] = 'page--taxonomy--term--product';

The only downside is that the whole term entity has to be loaded just to get the weight. As this entity is rendered later its possible, that its persistent at the time the hook function is triggered. But due to my lag of drupal knowledge i don't know where it might be.

  • use hasParameter() and getParameter() instead, that should give you the already loaded term object. However, I'm not sure that weight is really what you're looking for. Weight is for the order for a set of terms that have the same (or no parent). What you probably want is loadParents() from the taxonomy_term storage, that gives you the parent ID(s). – Berdir Mar 24 '15 at 20:26
  • Finding out the position in the hierarchy via parents and children seams to be the right way. But the functions loadParents() and loadChildren() are not giving me the ID(s), in fact there loading the Objects link. So the misapply of weights seamed to be the more performant way. Sadly there aren't functions like hasChildren(). – Dorian Mar 26 '15 at 9:36
  • if I want to do it by theme, I must put this code in template.php file like drupal 7? and the theme file name must be page_taxonomy_term_product.html.twig? am I right? – shekoufeh May 29 '19 at 12:19

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.