D8 如何检索 field--entity-reference.html.twig 文件的词汇术语上自定义字段的值?

D8 How do I retrieve the value of a custom field on a vocab term for the field--entity-reference.html.twig file?

我的目标是根据我添加到词汇表中的 field_topic_colour 对词汇术语进行颜色编码。还有其他词汇表没有这个字段。因此,我需要检查并查看某个术语是否存在,然后获取该值,以便我可以创建我的 类 并让按钮具有正确的颜色。

使用 kint 我可以看到该值,但我不知道如何在 twig 中或通过预处理深入到它。我发现的所有问题都处理节点中的词汇术语,而不是术语本身。

这是我的 kint 屏幕截图:

我正在尝试进入 field_topic_colour 下的 "primary"(这是告诉我的 Bootstrap 子主题使用什么颜色的关键字)。

预处理函数到底要写什么?

function MYTHEME_preprocess_field__entity_reference($variable) {
  //I need code to return a string like this (I think) where "primary"
  //is the value from my custom field in the term.
  $color = ????? (primary)
  $mytag = 'class="btn- . $color . ">TERM-NAME...TERM_URL...
}

我可以自己清理 php,在上面的例子中不用担心。我只需要获得我的领域的价值...

我已经检查了这里的备忘单:https://wizzlern.nl/sites/wizzlern.nl/files/artikel/drupal-content-entity-8.0.pdf 但似乎我真的需要一些具体的例子和解释为什么某些东西有效,所以我希望下次能开始逻辑地弄清楚它。

您可以像这样访问变量 $term->field_topic_colour->value 因为它在数组中,所以应该像这样访问 $term->field_topic_colour[0]->value

function MYTHEME_preprocess_field__entity_reference($variable) {
  $term = \Drupal::routeMatch()->getParameter('taxonomy_term');
  $color = NULL;
  if(isset($term->field_topic_colour[0]->value) {
    $color = $term->field_topic_colour[0]->value;
  }
  $mytag = 'class="btn- . $color . ">TERM-NAME...TERM_URL...
}

现在添加答案。我在领域的最终代码--entity-reference.html.twig file:

{% for item in items %}
  {% set mylabel %}
    {{ item.content }}
  {% endset %}
  {% set myclass %}
    {{ item.content['#options'].entity.vid.0.value['target_id'] }}
  {% endset %}
  {% set myclass = myclass|replace({'_':'-'}) %}
    <div{{ item.attributes.addClass('taxonomy--item') }}>
      <a class="btn-small btn-primary tag-{{ myclass|trim }}" href="{{ item.content['#url'] }}" role="button">{{ mylabel|striptags }}</a>
    </div>
{% endfor %}

HERE 是节点中访问 parent 节点中分类术语词汇表所需的代码。 (即,内容类型节点上的各个标签)。

item.content['#options'].entity.vid.0.value['target_id']

注意:这是在 Drupal 8.5.3 上,我的 "tags" 中的 none 有多个 parent.