0

I'm currently trying to figure out how to get the value of a field of a node in node.html.twig template. The field (machine_name: news) is linked to a taxonomy and multiple values can be selected. I see a lot of threads here on Drupal StackExchange - tried all the solutions, but not a single one fixes my problem.

I'm currently trying:

{{ node.field_news[0].value }}

But then nothing is printed. When I try:

{{ node.hasField('news') }}

... the value '1' is printed. So the field is available. I tried dumping the whole 'node' object using the Twig dump() method, but then I get a white-screen-of-dead due to memory restrictions.

Any idea's what is the correct way? I'm using Drupal 8.3.2

8
  • see drupal.stackexchange.com/questions/235490/…
    – 4uk4
    Commented May 24, 2017 at 9:31
  • @4k4 thnx, I already tried that one. My taxonomy doesn't have fields, so I tried {{ node.field_news.entity.label }}, but this doesn't print anything (return value is empty) Commented May 24, 2017 at 9:36
  • sure it has, name and description are core base fields
    – 4uk4
    Commented May 24, 2017 at 9:40
  • you use two versions for the machine name, `field_news' and 'news', you should choose only one of them
    – 4uk4
    Commented May 24, 2017 at 9:44
  • @4k4 {{ node.field_news.entity.name }} doesn't work either Commented May 24, 2017 at 9:45

1 Answer 1

1

I found the problem. The 'news' field is a multi-value selectable field. The correct way to access the field would be:

{{ content.news.0 }}

Of course, this will only print the first value in the collection, so I created a for loop in the twig template to loop over the different values.

I needed the 'title' and the 'url' of the taxonomy term. This could be retrieved by:

{{ content.news.0['#title'] }}
{{ content.news.0['#url'] }}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.