Hi,

I have a REST response that looks like this:

Array
(
    [0] => Array
        (
            [nid] => 24503
            [title] => 13.10
            [field_gita_10589_text] => Array
                (
                    [content] => some value

                          )

)

the key [field_gita_10589_text] is not fixed, and will change depending on checkboxes selected on a form. 

I have a twig file in which I am accessing the field_gita_10589_text.content like this:

<div class="container">
<h1> {{ data.field_gita_10589_text.content}} </h1>

But right now I am hard coding it. Since this is always the third key in the response, is there a way in which I can access just the third key in the response?

Thanks,

Comments

dibyajyoti.mallick’s picture

Hi,

In twig file you can first take key name(field_gita_10589_text) and set it output value.

https://stackoverflow.com/questions/24502935/getting-array-keys-in-twig-symfony/24502956

Thanks

wombatbuddy’s picture

{% set field = data|slice(2, 1)|first %}
<h1> {{ field.content }} </h1>
Saptaparnee’s picture

Ok. I understand the slice part, but what does '|first' do? 

Thanks, 

wombatbuddy’s picture

Do you use the 'kint' for exploring variables? 

{% set field = data|slice(2, 1) %}
{{ kint(field) }}

The screenshot of the result:
https://cdn1.imggmi.com/uploads/2019/11/14/285221ed212633f3f41806bebde3f...

{% set field = field|first %}
{{ kint(field) }}

The screenshot of the result:
https://cdn1.imggmi.com/uploads/2019/11/14/67095324f2accad0357ba5efe103f...

For more details see: 'How to Print Variables using Kint in Drupal 8'.

Saptaparnee’s picture

Thank you so much. I am not allowed to install kint, so thanks for the screenshots :)