Monday, April 20, 2009

Document paging with XSLT

Suppose you want to display a long XML document, with one part spanning multiple pages. This part could be - for example - displayed in a table, with header and footer repeated on every page. How to achieve this with XSLT? Very easily, in fact, using recursive template calls:


<xsl:template name="recursive">
<xsl:param name="start"/>
<xsl:param name="end"/>
<xsl:variable name="xml-doc"
select = "/path/to/data[position() > $start
and $end >= position() ]"/>

<xsl:if test="count($xml-doc) > 0">

<!-- template body goes here -->

<xsl:call-template name="recursive">
<xsl:with-param name="start" select="$end"/>
<xsl:with-param name="end" select="$end + $recordsPerPage"/>
</xsl:call-template>
</xsl:if>
</xsl:template>

That's it. The template calls itself recursively, dividing its content into separate parts. All you need to do is to define the recordsPerPage variable somewhere, and to call the template for the first time:


<xsl:call-template name="recursive">
<xsl:with-param name="start" select="0"/>
<xsl:with-param name="end" select="$recordPerPage"/>
</xsl:call-template>

No comments: