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?
It looks like the
conditionalRowStyle
template to add styles to the table is in the same stylesheet as the one building the table. If that's the case, then it will not work as expected, since the nodes selected in theconditionalRowStyle
template will be from the source document (containingsomeNode
) and not the target document (where the generated table elements are.)You can "hack" this by collecting the table output of the
someNode
templates to a variable first, which you can then run theconditionalRowStyle
template on first before finally outputting the variable value as the result of the stylesheet. But it's much simpler to use two stylesheets, that you run one after the other in a pipeline. The first stylesheet converts thesomeNode
data to a table, and the second appliesconditionalRowStyle
formatting to the table.You could probably get away with doing this in just css
If you cannot, you could do something like
Note that i wrote this in the SO textbox and haven't tested it.
This transformation:
when applied on this XML document:
produces the wanted result:
Do note:
We are using the most fine-grained traversal and processing of an XML document -- node by node. After the identity transformation this is the second most important XSLT design pattern.
The rest of the small tricks are not that important.