You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Drupal 8分类法区块Twig模板获取分类项并自定义样式求助

解决思路

你当前代码的核心问题是循环逻辑错误:直接遍历content并输出{{title}}完全无效,Drupal Views分类区块的术语数据不会存放在content根节点下,且title变量也未正确指向分类术语的标题。

步骤1:先排查数据结构

在模板中临时添加调试代码,查看content的实际结构:

{{ content|dump }}

刷新页面后,你会看到分类项的存储路径(绝大多数情况下是content.rows,也就是Views的结果行集合)。

步骤2:修正循环逻辑

根据调试结果调整循环,以常见的Views区块结构为例,正确的模板代码如下:

{%
set classes = [
'block',
'block-'~ configuration.provider|clean_class,
'block-'~ plugin_id|clean_class,
'clearfix',
]
%}

<div{{ attributes.addClass(classes) }}>
  {{ title_prefix }}
  {% if label %}
    <h2{{ title_attributes.addClass('block-title') }}>{{ label }}</h2>
  {% endif %}
  {{ title_suffix }}

  <ul class="taxonomy-sitemap-list">
    {% for row in content.rows %}
      {% set term = row.content['#row'] %}
      {# 生成自定义样式类,方便针对单个分类项设置样式 #}
      {% set term_classes = [
        'taxonomy-term-item',
        'term-id-' ~ term.tid.value,
        'term-slug-' ~ term.name|clean_class
      ] %}
      <li{{ create_attribute({'class': term_classes}) }}>
        {# 渲染分类术语的完整链接(包含标题) #}
        {{ row.content }}
      </li>
    {% endfor %}
  </ul>
</div>

步骤3:自定义单分类项样式

通过代码中生成的term-id-XXX、term-slug-XXX等类名,就可以在CSS中精准设置单个分类项的样式,示例:

.term-id-5 {
  color: #ff4444;
}
.term-slug-environment {
  font-weight: 700;
}

注意事项

  • 如果调试后发现分类项不在content.rows,就根据实际输出的结构调整循环对象(比如部分视图配置下可能是content.content)。
  • 不要直接硬编码变量名,始终先通过dump确认数据结构,避免因Views配置差异导致适配问题。

内容的提问来源于stack exchange,提问作者akhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 09:16:06