【问题标题】:Drupal 8 getting a referenced entity's field value in its parent in twigDrupal 8 在树枝中的父级中获取引用实体的字段值
【发布时间】:2016-10-20 23:36:26
【问题描述】:

这是我的设置。我有一个 自定义块类型,它有一个 reference entity 字段。它引用了“产品”的内容类型。 Products 内容类型具有对“系列”分类词汇的引用实体字段。

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

有没有办法严格从 twig 获得这个值?我尝试了无数的组合链试图达到它。

我有围绕产品的块--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>

然后转到我的字段--field-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>

【问题讨论】:

    标签: drupal-theming drupal-8


    【解决方案1】:

    1/ 您可以通过以下方式在节点模板级别获取它:

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

    如果你想要它作为一个数组...:

    {% 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
    

    【讨论】:

    • 谢谢!第二种方法有助于满足我的需要。
    猜你喜欢
    • 1970-01-01
    • 2019-11-24
    • 1970-01-01
    • 2018-08-25
    • 2021-04-23
    • 1970-01-01
    • 1970-01-01
    • 2020-04-05
    • 1970-01-01
    相关资源
    最近更新 更多