I've been playing around with XSLT today and wanted a quick and easy way to alternate the colors of list of items by using different applied css classes. After a bit of research I found you can use a mod function to figure this out. Check it out!

The following is an example of applying the classes "products-left" and "product-right" to a list item in a for-each

The Code:

                <xsl:for-each select="products/entry">
<li>
<xsl:attribute name="class">
<xsl:choose>
<xsl:when test="position() mod 2 = 1">products-left</xsl:when>
<xsl:otherwise>products-right</xsl:otherwise>
</xsl:choose>
</xsl:attribute>
</li>
</xsl:for-each>

              

The Output:

                <li class="products-left"></li>
<li class="products-right"></li>
<li class="products-left"></li>
<li class="products-right"></li>

              

You can see I used position() to well, figure out its position and then used a mod as my condition. Anything that didn't meet that condition would be thrown to the otherwise.

Comments welcome.