Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig for loop, how do I display the last element?

Tags:

twig

symfony

Here's my code.

<th>Attachment</th>
                <td>
                    <ul>
                        {% for attachment in lineup.attachments %}
                        <li><a href='http://files.example.com/{{ attachment.file_url }}'>{{ attachment.name }}</a>
                        {% endfor %}
                    </ul>
                </td>

This is posting EVERY attachment which is great but I just want it to post the last attachment it finds while iterating through the attachments table. For instance if it finds 10 attachments, I don't want all of them, just the 10th one. Is there anyway to do this?

like image 730
MikeOscarEcho Avatar asked Dec 19 '13 19:12

MikeOscarEcho


2 Answers

As of version 1.12.2 Twig contains a "last" filter The syntax is like this:

{{ array|last }}

In your situation it would be:

{{ lineup.attachments|last }}

You can use it like:

{% set attachement = lineup.attachments|last %}
<li>
    <a href='http://files.example.com/{{ attachment.file_url }}'>
       {{ attachment.name }}
    </a>
</li>

You can read all about it here: Twig documentation

like image 139
Robin Hermans Avatar answered Nov 15 '22 22:11

Robin Hermans


To add on to the accepted answer, there is no need to set it as a variable. This works too:

<a href='http://files.example.com/{{ lineup.attachments|last.file_url }}'>
  {{ lineup.attachments|last.name }}
</a>
like image 42
Jake Glascock Avatar answered Nov 15 '22 23:11

Jake Glascock