Reputation: 7157
I want to display XML content in a HTML table. I use the following (simplified) code to do so:
<xsl:template match="/">
<xsl:apply-templates select="/products/product">
<xsl:sort select="populariteit" order="descending" data-type="number"/>
</xsl:apply-templates>
</xsl:template>
<xsl:template match="product">
<xsl:if test="position()=1">
<table>
<tr>
<td>
<xsl:value-of select="title"/>
</td>
</tr>
</table>
</xsl:if>
</xsl:template>
With the following (simplified) XML:
<products>
<product>
<title>Title One</title>
<popularity>250</popularity>
</product>
<product>
<title>Title Two</title>
<popularity>500</popularity>
</product>
<product>
<title>Title Three</title>
<popularity>400</popularity>
</product>
</products>
What it does is sort the list by 'popularity', and then display the title from the first entry in the table (the most popular).
Now, what I want to accomplish is to display the titles from the first two popular items. But whatever I try, the XSLT outputs them in two different tables instead of one.
I've tried things like:
<xsl:template match="product">
<table>
<tr>
<td>
<xsl:if test="position()=1">
<xsl:value-of select="title"/>
</xsl:if>
<xsl:if test="position()=2">
<xsl:value-of select="title"/>
</xsl:if>
</td>
</tr>
</table>
</xsl:template>
But that results in two different tables; I want the titles to be displayed next to each other in the same table, while also still using the info from the sorted list.
My desired HTML output would be:
<table>
<tr>
<td>
Title Three Title Two
</td>
</tr>
</table>
It's important I use only use one XSL to generate this output, because of certain limitations in the software I'm using.
Upvotes: 0
Views: 338
Reputation: 167696
Well you will need to put the code generating the table in another template e.g.
<xsl:template match="/">
<table>
<tr>
<xsl:apply-templates select="/products/product">
<xsl:sort select="populariteit" order="descending" data-type="number"/>
</xsl:apply-templates>
</tr>
</table>
</xsl:template>
<xsl:template match="product">
<xsl:if test="position() < 3">
<td>
<xsl:value-of select="title"/>
</td>
</xsl:if>
</xsl:template>
That puts each title in a cell of its own, if you want all in one cell you would need to move the td
result element up to the other template as well and only output titles in the template for product
.
Upvotes: 2