Drupal 8 在树枝中的父项中获取引用实体的字段值

Drupal 8 getting a referenced entity's field value in its parent in twig

这是我的设置。我有一个 自定义块类型 ,它有一个 参考实体 字段。它引用 "Products" 的 内容类型 。 Products 内容类型有一个 taxonomy vocabulary of "Series".

的引用实体字段

系列分类法包含一个字段,我需要在我的自定义块的产品字段主题中获取该字段的值。我基本上有 5 个产品块,每个产品属于一个系列。在我的主题中,我需要为每个产品应用一个系列字段值。

有没有办法严格地从树枝中获取这个值?我尝试了无数组合链试图达到它。

我有我的 block--bundle--product_series_block.html.twig 围绕产品的文件。

<div {{ attributes.addClass(classes) }}
     data-ng-controller="ProductsController as vm">
  <div class="container">
    {{ title_prefix }}
    {% if label %}
      <h2{{ title_attributes }}>{{ label }}</h2>
    {% endif %}
    {{ title_suffix }}
    <div class="product-holder">
      {% block content %}
        {{ content }}
      {% endblock %}
    </div>
  </div>
</div>

然后转到我的字段--字段-products.html.twig,我想在其中获取用于数据系列 html 属性的系列。

<div{{ attributes.addClass(classes, 'field__items') }} data-series="{{ cant_figure_this_out }}">
  {% for item in items %}
    <div{{ item.attributes.addClass('field__item item') }}>{{ item.content }}</div>
  {% endfor %}
</div>

1/ 你可以在节点模板级别用这样的东西得到它:

node.field_serie.0.get('entity').getTarget().getValue().getName()

如果你想要它作为一个数组...:[=​​14=]

{% set series = [] %}
{% for key, item in node.field_serie %}
  {% set series = series|merge( [item.get('entity').getTarget().getValue().getName()] )  %}
{% endfor %}

2/ 也可以在字段模板级别获取:

{% set series = [] %}
{% for key, item in item['content']['#node'].field_serie %}
  {% set series = series|merge( [item.get('entity').getTarget().getValue().getName()] )  %}
{% endfor %}

3/ 然后你可以使用类似的东西(这可能需要更多的工作):

attributes.setAttribute('data-series', series|join(',')|escape