Tip: Switching between odd and even items in templates

There are a few little gems in the Perch templating engine that are easy to miss in the documentation. One such gem is the special ID value perch_item_odd. For template that output multiple items (like a multi-item region, or a blog post listing), this enables you to do something different for even and odd items.

Take the simple example of adding a class to alternatively stripe items in a list:

<li class="<perch:content id="perch_item_odd" />"> ... </li>

For odd items, this would output:

<li class="odd"> ... </li>

and for even items:

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

You can get even more creative by testing for perch_item_odd with a conditional tag:

<perch:if exists="perch_item_odd">
    this part of the template is for odd items only
<perch:else />
    and this part is just for even items
</perch:if>

The documentation for perch_item_odd is in the Template Manual with the information about the ID attribute