How to get the first element of an array in Twig?

by aliyah.nikolaus , in category: PHP , 2 years ago

I have an array of translations in my Twig template and the first element is default translation, how can I get the first element of an array in Twig to show the name of the default translation before the loop?


Code:

1
2
3
4
5
6
{% for translation in translations %}
    <tr>
        <td>{{ loop.index }}</td>
        <td>{{ translation.name }}</td>
    </tr>
{% endfor %}


Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Y

Member

by yorkiepup , 2 years ago

@aliyah.nikolaus You have probably only 2 solutions: The first is just access by key or index. The other one(I think it's better) is to use filter "first" to get the first element of any array in Twig:

Your solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<p>{{ translations|first }}</p>

{# it works with method as well #}
<p>Default Translation Name: 
    <span>{{ translations|first.name }}</span>
</p>
{% for translation in translations %}
    <tr>
        <td>{{ loop.index }}</td>
        <td>{{ translation.name }}</td>
    </tr>
{% endfor %}

Member

by wiley , 8 months ago

@aliyah.nikolaus 

Your solution is almost correct. However, accessing the attribute name directly on translations|first won't work because translations|first will return the entire object, not just the name.


To get the name of the default translation, you need to access the name attribute on the object returned by translations|first using the dot notation.


Corrected code:

1
2
3
Default Translation Name: 
    {{ translations|first.name }}


This will correctly display the name of the default translation before the loop.