在page.html.twig中使用如下代码调用分类术语名称:
{% if node %}{# 判断当前页面是不是文章内容页 #}
{% if node.field_category %} {# field_category是文章归属的分类术语的字段名称 #}
{% for term in node.field_category %}
{{ term.entity.label }}
{% endfor %}
{% endif %}
{% else %}
{# 如果不是文章内容页获取的方法比较麻烦一点 #}
{{ taxonomy_term_name }}
{% endif %}
如果不是在文章内容页中,需要在.theme
文件中添加预处理方法:
function blog_preprocess_page(&$variables) {
// 检查当前页面是否是分类页面
if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical') {
// 获取当前分类页面的分类实体
$taxonomy_term = \Drupal::routeMatch()->getParameter('taxonomy_term');
// 检查是否成功获取分类实体
if ($taxonomy_term instanceof \Drupal\taxonomy\TermInterface) {
// 将分类名称添加到模板变量中
$variables['taxonomy_term_name'] = $taxonomy_term->getName();
}
}
}
在模板中使用{{ taxonomy_term_name }}
显示分类名称。