Drupal Twig模板传递tid变量生成路径报错问题求助
解决Drupal分类术语View页面添加基于路径别名的CSS类问题
你遇到的核心问题是Twig模板解析时,tid变量还未被正确赋值,导致path()函数调用失败。下面提供几个无需JS的可靠解决方案:
方案1:通过View字段传递术语实体到模板
- 编辑你的分类术语View,添加Taxonomy term: Term entity字段,设置为「Exclude from display」(不显示在页面上)
- 在
views-view.html.twig模板中,通过该字段获取术语实体并生成CSS类:
{# 获取术语实体 #} {% set term_entity = fields['term_entity'].content['#term'] ?? null %} {% if term_entity %} {# 获取路径别名 #} {% set term_alias = path('entity.taxonomy_term.canonical', {'taxonomy_term': term_entity.id()}) %} {# 转换为合法的CSS类名(去除斜杠、转小写、添加前缀) #} {% set term_class = 'term-' ~ term_alias|replace({'/': '-'})|lower|trim('-') %} {% else %} {% set term_class = '' %} {% endif %} {# 将类名添加到容器的class属性中 #} <div class="{{ classes }} {{ term_class }}"> {{ title_prefix }} {% if title %} {{ title }} {% endif %} {{ title_suffix }} {{ rows }} {{ empty }} {{ pager }} </div>
方案2:用预处理函数(推荐,更稳定)
通过自定义模块的预处理函数在PHP层面处理,避免Twig上下文变量缺失的问题:
- 在你的自定义模块(比如
mymodule)的.module文件中添加以下代码:
function mymodule_preprocess_views_view(&$variables) { $view = $variables['view']; // 仅针对你的分类术语View(替换为实际的View机器名) if ($view->id() !== 'taxonomy_term') { return; } // 从View参数中获取tid $tid = $view->args[0] ?? null; if (!$tid) { return; } // 加载术语实体 $term = \Drupal\taxonomy\Entity\Term::load($tid); if (!$term) { return; } // 获取路径别名 $alias_manager = \Drupal::service('path_alias.manager'); $alias = $alias_manager->getAliasByPath('/taxonomy/term/' . $tid); // 转换为合法CSS类名 $class = 'term-' . str_replace('/', '-', trim($alias, '/')); $class = strtolower($class); // 将类名添加到View的classes数组 $variables['classes'][] = $class; }
- 清除Drupal缓存后,你的分类术语View页面的容器会自动带上生成的CSS类,无需修改Twig模板。
为什么原方法失效?
在Twig模板中直接调用path()时,模板上下文可能还未加载到tid变量——View的参数是在预处理阶段才传递到模板变量中的,直接在模板中引用tid会因变量未初始化导致参数为空。上述两种方案都是在能可靠获取tid/术语实体的阶段处理,避免了这个问题。
内容的提问来源于stack exchange,提问作者Stanislav Kniazev
相关产品推荐
相关产品推荐

