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

D8:如何在field--entity-reference.html.twig获取词汇术语自定义字段值?

解决Drupal词汇术语自定义字段在实体引用模板中获取的问题

我懂你现在的痛点——想给词汇术语做颜色编码,但自定义字段field_topic_colour在Twig模板或者预处理里死活找不到,而且搜了一圈都是讲节点里引用词汇的情况,完全不是你现在这种在实体引用字段模板里直接处理术语字段的场景。别慌,我给你两个靠谱的解决方案:

方法一:通过预处理函数传递字段值(推荐,性能更优)

最稳妥的方式是在主题的.theme文件里加个预处理函数,把词汇术语的自定义字段值主动传到模板里:

  1. 打开你的主题文件(比如mytheme.theme),添加这段代码:
function mytheme_preprocess_field__entity_reference(&$variables) {
  // 遍历每个实体引用项
  foreach ($variables['items'] as &$item) {
    // 先拿到对应的词汇术语实体
    $term = $item['content']['#options']['entity'] ?? NULL;
    if ($term) {
      // 关键:先检查术语有没有这个字段,再检查字段是否不为空
      if ($term->hasField('field_topic_colour') && !$term->get('field_topic_colour')->isEmpty()) {
        // 根据你的字段类型取值,这里假设是文本类型的颜色码
        $colour_value = $term->get('field_topic_colour')->value;
        // 把颜色值传到模板变量里,方便Twig调用
        $item['content']['#topic_colour'] = $colour_value;
        // 也可以直接生成预定义的类名,省得Twig里再处理
        $item['attributes']['class'][] = 'topic-colour--' . str_replace('#', 'hex-', $colour_value);
      }
    }
  }
}

记得把mytheme换成你的实际主题名,要是field_topic_colour是颜色选择器模块的字段,可能要改成$term->get('field_topic_colour')->hex->value这类取值方式,根据字段类型调整就行。

  1. 接着在field--entity-reference.html.twig里就能直接用这个变量了:
{% for item in items %}
  <button{{ item.attributes.addClass('topic-button') }}>
    {{ item.content }}
    {% if item.content['#topic_colour'] %}
      {# 要是需要直接用颜色值写内联样式也可以 #}
      <style>.topic-button { background-color: {{ item.content['#topic_colour'] }}; }</style>
    {% endif %}
  </button>
{% endfor %}

方法二:直接在Twig模板中加载实体(适合小数据场景)

如果不想改.theme文件,也可以在Twig里直接加载术语实体,但这种方式性能稍弱,适合引用项不多的情况:

{% for item in items %}
  {% set term_id = item.content['#options']['entity']?.id() %}
  {% if term_id %}
    {# Drupal 8+推荐用实体类型管理器加载,替代弃用的term_load() #}
    {% set term = Drupal.entityTypeManager.getStorage('taxonomy_term').load(term_id) %}
    {% if term and term.hasField('field_topic_colour') and not term.field_topic_colour.isEmpty() %}
      {% set colour = term.field_topic_colour.value %}
      <button class="topic-button topic-colour--{{ colour|replace({'#': 'hex-'}) }}">
        {{ item.content }}
      </button>
    {% else %}
      <button class="topic-button">
        {{ item.content }}
      </button>
    {% endif %}
  {% else %}
    <button class="topic-button">
      {{ item.content }}
    </button>
  {% endif %}
{% endfor %}

关键注意事项

  • 一定要先做双重检查:术语是否存在该字段(hasField('field_topic_colour'))、字段是否不为空(!isEmpty()),避免出现实体不存在或字段为空的报错。
  • 用Kint调试的时候,在预处理里加kint($term),或者在Twig里写{{ kint(item.content['#options']['entity']) }},就能清晰看到字段的结构了。
  • 如果是颜色选择器类的字段,取值方式要对应调整,比如Color Field模块的字段要取hex子字段的值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:55:57