开发者

Loop xslt template

I know there are similar, more complex posts around, but I just can't get this simple thing to work. I have a very very simple XSLT loop, which I just need to run 5 times over. That's it.

Here's what I have:

<xsl:template match="/">
  <div id="container">
    <xsl:for-each select="$currentPage/myItems/data/item">
      <img src="image.gif" />
    </xsl:for-each>
  </div>
</xsl:template>

This works fine, I just need to loop this part:

    <xsl:for-each select="$currentPage/myItems/data/item">
      <img src="image.gif" />
    </xsl:for-each>

five times over, so that the output is 开发者_StackOverflow中文版literally just repeated 5 times. I don't want to just copy and paste it five times (although that does work) as there's got to be a better way to handle it.

Can anyone point me in the right direction on this? Thanks!


Technically, XSLT is intended for transformation of data; looping a predetermined number of times would fall more in line with generation of data. The appropriate way would, unfortunately, be to copy and paste it 5 times.

Plus, you probably spent more time asking this question than it would have taken to copy and paste :)


The only imperative looping construct in XSLT is for-each but that loops over nodes in the input document. If you don't want to implement using recursion, put the inside of the loop in a named template and then use call-template five times to call it.

Something like:

<xsl:template name='inside-loop'>
  <xsl:for-each select="$currentPage/myItems/data/item">
    <img src="image.gif" />
  </xsl:for-each>
</xsl:template>

and then where you want to call this:

<xsl:call-template name='inside-loop' />


Sorry, but what's the difference with using:

<xsl:template match="/">
  <div id="container">
    <xsl:for-each select="$currentPage/myItems/data/item">
      <img src="image.gif" />
      <img src="image.gif" />
      <img src="image.gif" />
      <img src="image.gif" />
      <img src="image.gif" />
    </xsl:for-each>
  </div>
</xsl:template>

or, better:

<xsl:template match="/">
  <div id="container">
        <xsl:apply-templates select="$currentPage/myItems/data/item" mode="image"/>
  </div>
</xsl:template>

<xsl:template match="item" mode="image">
    <img src="image.gif" />
    <img src="image.gif" />
    <img src="image.gif" />
    <img src="image.gif" />
    <img src="image.gif" />
</xsl:template>


In XSLT 2.0, you can do:

<xsl:for-each select="1 to $n">
   ....
</xsl:for-each>

In 1.0 you have a choice: you can use recursion (the template calls itself passing a count as a parameter, and terminates when the count drops to zero); or you can use the workaround

<xsl:for-each select="(//node())[position() &lt;= $n]">

provided there are more than $n nodes in your document.

Of course, as others have pointed out, if $n is always and forever will always be 5, you can just replicate the code 5 times.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜