these is my xml
<elemetns>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
...
<item>...</item>
<elemetns>
the out put shoud create a html table with 4 colums
<xsl:template match="Item" mode="single">
from current position 4 items and build the first row with item data
</xsl:template>
Any ideas?
The following approach should help:
<xsl:template match="elements">
<table>
<tbody>
<xsl:apply-templates select="item[position() mod 4 = 1]" mode="row"/>
</tbody>
</table>
</xsl:template>
<xsl:template match="item" mode="row">
<tr>
<xsl:apply-templates select=". | following-sibling::item[position() < 4]" mode="cell"/>
</tr>
</xsl:template>
<xsl:template match="item" mode="cell">
<td>
<xsl:value-of select="."/>
</td>
</xsl:template>
Another way to do it with xslt 1.0 is to use keys:
Given this XML:
<?xml version="1.0" encoding="UTF-8"?>
<elements>
<item>r1c1</item>
<item>r1c2</item>
<item>r1c3</item>
<item>r1c4</item>
<item>r2c1</item>
<item>r2c2</item>
<item>r2c3</item>
<item>r2c4</item>
<item>r3c1</item>
<item>r3c2</item>
<item>r3c3</item>
</elements>
the following stylesheet
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes" method="html"/>
<xsl:key name="items-by-row" match="elements/item"
use="floor(count(preceding-sibling::item) div 4) + 1"/>
<xsl:template match="/">
<table>
<xsl:apply-templates select="//item[position() mod 4 = 1]" mode="row"/>
</table>
</xsl:template>
<xsl:template match="item" mode="row">
<tr>
<xsl:apply-templates select="key('items-by-row', position())" mode="cell"/>
<xsl:variable name="span" select="4 - count(key('items-by-row', position()))"/>
<xsl:if test="$span > 0">
<xsl:call-template name="handle-colspan">
<xsl:with-param name="span" select="$span"/>
</xsl:call-template>
</xsl:if>
</tr>
</xsl:template>
<xsl:template name="handle-colspan">
<xsl:param name="span"/>
<!--suppress CheckTagEmptyBody -->
<td>
<xsl:if test="$span > 1">
<xsl:attribute name="colspan">
<xsl:value-of select="$span + 1"/>
</xsl:attribute>
</xsl:if>
</td>
</xsl:template>
<xsl:template match="item" mode="cell">
<td>
<xsl:apply-templates/>
</td>
</xsl:template>
</xsl:stylesheet>
produces the following result:
<table>
<tr>
<td>r1c1</td>
<td>r1c2</td>
<td>r1c3</td>
<td>r1c4</td>
</tr>
<tr>
<td>r2c1</td>
<td>r2c2</td>
<td>r2c3</td>
<td>r2c4</td>
</tr>
<tr>
<td>r3c1</td>
<td>r3c2</td>
<td>r3c3</td>
<td></td>
</tr>
</table>
Please note that with the handle-colspan
template I'm inserting additional td
elements in order to produce correct tables.