Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xslt how to style conditional odd/even rows

I've an html table written using xslt transformation that looks like this

<table>
    <xsl:for-each select="someNode">
        <xsl:if test="testThis">
            <tr>
                <!-- <xsl:call-template name="conditionalRowStyle"/> -->
                <td>something</td>
            </tr>
         </xsl:if>
         <tr>
             <!-- <xsl:call-template name="conditionalRowStyle"/> -->
             <td>this is always displayed</td>
         </tr>
         <xsl:if test="testThis2">
            <tr>
                <!-- <xsl:call-template name="conditionalRowStyle"/> -->
                <td>something 2</td>
            </tr>
         </xsl:if>
         ....
    </xsl:for-each>
    <tr>
        <!-- <xsl:call-template name="conditionalRowStyle"/> -->
        <td>this is always displayed</td>
    </tr>
</table>

I need a way to apply different classes oddRow/evenRow to tr elems.

<tr class="evenRow"> or <tr class="oddRow">

I tried to use a template like this after every <tr> elem

<xsl:template name="conditionalRowStyle">
    <xsl:attribute name="class">
        <xsl:choose>
            <xsl:when test="(count(../preceding-sibling::tr) mod 2) = 0">oddrow</xsl:when>
            <xsl:otherwise>evenrow</xsl:otherwise>
        </xsl:choose>
    </xsl:attribute>
</xsl:template>

but this is not working. any idea?

like image 579
mickthompson Avatar asked Jul 15 '10 10:07

mickthompson


1 Answers

You could probably get away with doing this in just css

tr:nth-child(odd) {
    /*...*/
}
tr:nth-child(odd) {
    /*...*/
}

If you cannot, you could do something like

<xsl:attribute name="class">
    <xsl:choose>
        <xsl:when test="(position() mod 2) != 1">
            <xsl:text>evenRow</xsl:text>
        </xsl:when>
        <xsl:otherwise>
            <xsl:text>oddRow</xsl:text>
        </xsl:otherwise>
    </xsl:choose>
</xsl:attribute>

Note that i wrote this in the SO textbox and haven't tested it.

like image 191
Kris Avatar answered Oct 06 '22 00:10

Kris