When generating styled HTML output from XML, you might need to attach a special class to the first and/or the last element in a series (for example, first and last child). An only child would obviously have both classes attached to it (don't forget,
class attribute can list multiple classes separated by a whitespace). The code to generate optimal list of HTML classes (or doing a generic
join of list elements) is pretty simple:
<xsl:variable name="class">
<xsl:if test="position() = 1"> FirstInSeries</xsl:if>
<xsl:if test="position() = last()"> LastInSeries</xsl:if>
</xsl:variable>
<xsl:if test="$class != ''">
<xsl:attribute name="class">
<xsl:value-of select="substring-after($class,' ')" />
</xsl:attribute>
</xsl:if>
Please note the following:
- Each value in the list has a leading whitespace. The list values are thus properly separated, but the result has an extra leading whitespace.
- The last xsl:if instruction tests if the class attribute is needed (detailed description of this trick).
- The substring-after function removes the leading whitespace, resulting in the desired value for the class attribute.
No comments:
Post a Comment