I normally use jquery templates for this sort of thing but I inherited an XSLT file I need to update but I can't find a way to get the total number of elements (iterations) for a specific template call.
With jquery templates I'd do something like this and it would give me total number of assets that I'm looping through.
<span id="${spnID}">
${GroupName} (${Assets.length})
</span>
This would return me "Product x (5)" if there were five elements in the loop.
It seems simple but I can't seem to find a way to do the same thing with XSLT. Something like this, I think:
<span id="{$SpnId}">
<xsl:value-of select="$GroupName"/> (<xsl:value-of select="$total-number-of-elements"/>)
</span>
If you're looping over some $set
then output count($set)
to get the total number of items to be iterated. For example, try this stylesheet:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" />
<xsl:template match="/">
<xsl:variable name="set" select="/table/row" />
<xsl:variable name="count" select="count($set)" />
<xsl:for-each select="$set">
<xsl:value-of select="concat(position(), ' of ', $count, '
')" />
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
Against this input:
<table>
<row id="1" />
<row id="2" />
<row id="3" />
<row id="4" />
<row id="5" />
<row id="6" />
</table>
Output:
1 of 6
2 of 6
3 of 6
4 of 6
5 of 6
6 of 6
Note that we're looping over the nodes selected by /table/row
and outputting count(/table/row)
to get the number of iterations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With