Tip: Identifying first and last items in a template

In a similar way to yesterday’s tip where we saw how the odd and even items in a multiple-item template can be picked out, it’s also possible to identify the first and last items.

The special ID values perch_item_first and perch_item_last enable us to do this. Whilst they don’t output anything on their own, they can be used in a conditional tag:

<perch:if exists="perch_item_first">
    ... this is the first item ...
</perch:if>

This can be useful when working with a CSS framework that needs you to put a different class on the first and last items in a set, for example.

<li class="first">...</li>
<li>...</li>
<li>...</li>
<li>...</li>
<li>...</li>
<li class="last">...</li>

The trick here is that we need to be able to output three different states; the first, the last and the default state for the items in the middle. We can achieve this by nesting our IF statements.

<perch:if exists="perch_item_first">
    <li class="first">
<perch:else />
    <perch:if exists="perch_item_last">
        <li class="last">
    <perch:else />
        <li>
    </perch:if>
</perch:if>
    ...
    </li>

Perch IF tags can be nested up to 10 items deep, although that would make for quite a complex template.