Jason
Jason

Reputation: 396

Twig Markup - Pulling out Variables

Im new to twig and having a hard time getting what I need out of an array.

Here is my output from

{{ dump(items) }}

array (size=1)
  0 => 
    array (size=2)
      'content' => 
        array (size=4)
          '#type' => string 'processed_text' (length=14)
          '#text' => string '8AS09DF8a90sd80' (length=15)
          '#format' => string 'basic_html' (length=10)
          '#langcode' => string 'en' (length=2)
      'attributes' => 
        object(Drupal\Core\Template\Attribute)[2249]
          protected 'storage' => 
            array (size=0)
              ...

So I have an object(i think) with nested info inside of it

Ive tried:

{{ dump(items[0]) }}

{{ dump(items['content']) }}

{{ items.content }}

{{ items.['content']['text'] }}

and a bunch of other formats, nothing works!!

How do I structure this in twig?

Upvotes: 1

Views: 985

Answers (1)

A.L
A.L

Reputation: 10503

This should work:

{{ items.0.content['#langcode'] }}

We need to use:

  • 0 to select the first key of the items array
    • content to select the content node
      • #langcode to get the value with #langcode key

Where . and [] have the same role: they are used to access to an attribute of an object, in this case the value associated to a key in an array. But writing items.0.content.#langcode would trigger a syntax error because # is not a valid character (1), so we have to use the other syntax ['#langcode'].

Source: Official documentation.

(1): I didn't tested but I'm pretty sure of this.

Upvotes: 1

Related Questions