Drupal 8 - How to access user profile field from node twig

By xngo on July 1, 2019

In this tutorial, I will show you how you can access user fields from the node twig template file.

Let me use my example. I created a new field called field_user_hobbies from Configuration > Account settings > Manage fields.

User field setting: Hobbies

In my ./themes/YOUR_THEME/templates/node--article.html.twig file, I can access the content of the hobby field using the indices. Here are the examples.

Access the first element.
{{ node.uid.entity.field_user_hobbies[0].value }}
 
This is another way to access the first element too.
{{ node.uid.entity.field_user_hobbies.0.value }}

Or, I can loop through all the values of that field.

{%- for item in node.uid.entity.field_user_hobbies -%}
    {{ item.value }}
{%- endfor -%}

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.