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?
-
Differently in which way?– sanzanteMar 27, 2015 at 10:01
-
You can use the TVI module (drupal.org/project/tvi) to assign a View on the lower hierarchy. Then, use the "Template suggestions" on the Context module (drupal.org/project/context) and assign it to that View.– CocoSkinJan 25, 2021 at 18:35
2 Answers
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')
?– DorianMar 24, 2015 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).– BerdirMar 24, 2015 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().– DorianMar 26, 2015 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? May 29, 2019 at 12:19