Smarty Tip for Cycling Classes

There are many situations in our custom web application development where we need to cycle through a series of classes (usually with table row for displaying data, or similar).

In the Smarty PHP Template Engine that we use in almost all of our custom applications, we used to do something like this:

class="{if $myId is even}even{else}odd{/if}"

And if there was more than two classes to cycle through, then we had if/else’s with mod operations. Not very clean.

However, I just realized Smarty has an even better way of doing this, with their Cycle operation:

class="{cycle values="odd,even"}"

This is a lot less work, especially if you needed to cycle through, say 6 classes. Maybe this will help someone else down the line.



Posted in PHP, Smarty