Let’s say I have this XML node:
<items>
<item>...<item>
<item>...<item>
<item>...<item>
<item>...<item>
<item>...<item>
...
</items>
where there are N item nodes.
Now I would like to transform it into an HTML table with 4 columns. (e.g. if N=12, there are 3 complete rows, and if N=27, there are 7 rows, the last having 3 cells)
How could I go about doing this?
My gut call is to do it this way, where {{something}} is what I don’t know how to implement:
<xsl:template match="items">
<table>
<xsl:call-template name="partition-items">
<xsl:with-param name="skip" select="0" />
</xsl:call-template>
</table>
</xsl:template>
<xsl:template name="partition-items">
<xsl:param name="skip" />
{{ if # of items in current node > $skip,
output a row,
and call partition-items($skip+4)
}}
<xsl:template />
The pieces I don’t know how to implement, are
- how to make a predicate for testing the # of
itemelements in the current node - how to get the Nth
itemelement in the current node
Update from comments
How to pad the last row with empty
<td />elements so that each row
contains exactly the wanted cells?
That’s my working solution.
As you didn’t provide a desired output, this particular one may be uncomplete for your needs.
Test input:
Output:
Do note: you can pass columns number dynamically.
Additional requirements and edit.
It can be applied to the previous sample or to this concise XML:
Result will be:
Do note:
itemelements than number of columns is.If there won’t ever be less elements than number of columns, you can just apply to the
itemelements with the same predicate and a differentmode.And last edit. With a counted loop.