Accessing deep values from array

996 views Asked by At

I have a basic template node--some-name.html.twig, which I am trying to access a specific value from a child of the content variable.

{% for item in content %}
  {{ kint(item) }}
{% endfor %}

which prints an expected value like so (trimmed for brevity):

Array
(
    [#title] => Body
    [#language] => en
    [#field_name] => body
    [#field_type] => text_with_summary
    [#field_translatable] => 1
    [#entity_type] => node
    [#object] => stdClass Object
        (
            [__CLASS__] => Drupal\node\Entity\Node
            [in_preview] => 
            [values:protected] => Array
                (
                    [body] => Array
                        (
                            [x-default] => Array
                                (
                                    [0] => Array
                                        (
                                            [value] => Body sample goes here
                                            [summary] => summary sample here
                                            [format] => rich_text
                                        )

                                )

                        )
                )
        )
)

but if I try to print them in my loop it only returns null... am I missing something super basic?

{% for item in content %}
  {{ item["#object"].values.body[0].value }}
  {{ item["#object"]["values"]["body"][0].value }}
{% endfor %}

printing {{item}} gives the entire item as expected but trying to access specific deeper properties of item seems to be null regardless of property or how I've accessed it.

Any help would be appreciated.

1

There are 1 answers

0
DarkBee On

The property values in your class is protected, meaning twig will not be able to access this property unless:

  • You make the property values public
  • You create a public getter getValues in your class

As seen in the documentation