Drupal 8 - how to access field values nested deep inside an array structure

3.4k Views Asked by At

I am trying to access values of a content type nested deep into array. This is the actual scenario:

I want to customise the default search result page layout of Drupal 8 with additional field information. To know what fields are available for me to access I used {{ kint(item.value) }}, which shows me this:

enter image description here

Fields I want to access are nested under #result>node>fields like body, field_category etc.

Is there any way I can access them directly inside my twig template? I was guessing something like {{ item.value['node']['fields']['field_name']} }? but this gave me nothing!

There is every possibility that the way I am thinking is not a suitable method or may be even not a method at all! I am still very new to Drupal.

All I want is to access desired fields nested deep below inside an array structure. Is there a kind of thumb rule or syntax to follow? Is there a process to access a specific element from inside a nested Drupal array?

Note: In order to customise layout I copied item-list.html.twig file from /core/themes/stable/templates/dataset to my theme's templates folder.

Drupal version: 8.2.3

Edit

Template file for search result (item-list.html.twig)

<p class="righteous">Makes sure the page is being hit!</p>

{% if context.list_style %}
    {%- set attributes = attributes.addClass('item-list__' ~ context.list_style) %}
{% endif %}
{% if items or empty %}
    {%- if title is not empty -%}
        <h3>{{ title }}</h3>
    {%- endif -%}

    {%- if items -%}
        <{{ list_type }}{{ attributes }}>
        {%- for item in items -%}
            <li{{ item.attributes }}>{{ content.body }}</li>
        {%- endfor -%}
        </{{ list_type }}>
    {%- else -%}
        {{- empty -}}
    {%- endif -%}
{%- endif %}
1

There are 1 best solutions below

5
Gabbax0r On

If you want to render specific fields from a template you have to use for example:

{{ content.field_feature }}

you can see in your array or in the UI of d8 the machine names of your fields.

{{ content.field_<machine-name> }}

with this you can access your array and theme your content type yourself.