首页 > 解决方案 > D8 如何在 field--entity-reference.html.twig 文件的词汇术语中检索自定义字段的值?

问题描述

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

使用 kint 我可以看到价值,但我无法弄清楚如何在树枝中或通过预处理深入研究它。我发现的所有问题都处理节点中的词汇术语,而不是术语本身。

这是我的 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但似乎我真的需要一些具体的例子和解释为什么会起作用,所以我希望下次可以开始在逻辑上弄清楚。

标签: entitydrupal-8preprocessorvocabularytwig-filter

解决方案


您可以像这样访问变量$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...
}

推荐阅读