Reputation: 67
I want to loop my template according to user selection but I cant find a way to loop it
xml file:
<?xml version="1.0" encoding="UTF-8"?>
<movies>
<cd>
<title>Batman</title>
</cd>
<cd>
<title>Ironman</title>
</cd>
</movies>
showMovies.php:
<?php
header('Access-Control-Allow-Origin: *');
header('Content-type: application/xml');
$countMovie= $_GET['countMovie'];
?>
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<xsl:variable name="total" select="count(/movies/title)" /> //count total movie
<html>
<body>
<xsl:for-each select="movies/cd">
<tr>
<td><xsl:value-of select="title"/></td>
</tr>
</xsl:for-each>
<xsl:if test="$total < <?php echo $countMovie; ?>"> //check if total movie less than $countMovie
No more movie
</xsl:if>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
(If $countMovie=5)
Current result:
Batman
Ironman
No more movie
Expected result:
Batman
Ironman
No more movie
No more movie
No more movie
I know I need to use <xsl:template>
and keep calling the template but I tried several times and still fail to do so. How to do a for loop by using template? Thanks
Upvotes: 0
Views: 216
Reputation: 117165
Not sure what you mean by "user selection". There is no user interaction in XSLT.
If you want, you can pass a parameter to the stylesheet and use it in a recursive named template to generate the required number of rows:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:param name="rows"/>
<xsl:template match="/movies">
<html>
<body>
<table border="1">
<xsl:call-template name="generate-rows"/>
</table>
</body>
</html>
</xsl:template>
<xsl:template name="generate-rows">
<xsl:param name="i" select="1"/>
<xsl:if test="$i <= $rows">
<xsl:variable name="cd" select="cd[$i]" />
<tr>
<td>
<xsl:choose>
<xsl:when test="$cd">
<xsl:value-of select="$cd/title"/>
</xsl:when>
<xsl:otherwise>No more movie</xsl:otherwise>
</xsl:choose>
</td>
</tr>
<!-- recursive call -->
<xsl:call-template name="generate-rows">
<xsl:with-param name="i" select="$i + 1"/>
</xsl:call-template>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
If your calling application passes 5
as the rows
parameter, then the result will be:
<html>
<body>
<table border="1">
<tr>
<td>Batman</td>
</tr>
<tr>
<td>Ironman</td>
</tr>
<tr>
<td>No more movie</td>
</tr>
<tr>
<td>No more movie</td>
</tr>
<tr>
<td>No more movie</td>
</tr>
</table>
</body>
</html>
Upvotes: 1