MikeOscarEcho
MikeOscarEcho

Reputation: 548

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

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?

Upvotes: 8

Views: 16932

Answers (2)

Robin Hermans
Robin Hermans

Reputation: 1599

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

Upvotes: 23

Jake Glascock
Jake Glascock

Reputation: 41

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>

Upvotes: 3

Related Questions