Search

Hi,

I’m looping through article entries. I need each iteration of my for-each to have a number, 1 through 4, when the loop will terminate.

I’m a super noob at XSL. How can I set a variable outside of the loop to 1, then have it increment by 1 in each iteration?

Thanks

You’ll likely want to do this with a recursive template. It’s the XSLT version of loops in procedural programming languages.

It’s quite verbose, but it can be quite powerful.

<xsl:template name="recursive-counting">
    <xsl:param name="count" select="1"/>
    <xsl:param name="num" select="9"/>

    <p><xsl:value-of select="$num"/></p>

    <xsl:if test="$count &lt; $num">
        <xsl:call-template name="recursive-counting">
            <xsl:with-param name="count" select="$count + 1" />
            <xsl:with-param name="num" select="$num" />
        </xsl:call-template>
    </xsl:if>
</xsl:template>

Sorry, I reread your question, and realized I may have lead you astray.

Try something like this:

<xsl:for-each select="/data/articles/entry">
    <li><a>Article Number <xsl:value-of select="position()"/></a></li>
</xsl:for-each>

If you only want the first four articles, you can modify the for-each:

<xsl:for-each select="/data/articles/entry[position() &lt;= 4]">
...
</xsl:for-each>

Which means “loop through each entry where its position is less than or equal to 4”. Notice the less than symbol, usually < is encoded as its HTML entity, so it becomes valid XML.

If you want a more advanced way of achieving this — a for loop when you don’t have any XML to loop through — a colleague and I devised a way of using a generic recursive counting template (as bauhouse exampled above), which calls another template to write out the HTML for each iteration in the loop. It’s probably not relevant for your example, but may be useful reading in the future.

Ohhhhh @bauhouse, you made my day, well evening … :) Cheers a 1000!

Create an account or sign in to comment.

Symphony • Open Source XSLT CMS

Server Requirements

  • PHP 5.3-5.6 or 7.0-7.3
  • PHP's LibXML module, with the XSLT extension enabled (--with-xsl)
  • MySQL 5.5 or above
  • An Apache or Litespeed webserver
  • Apache's mod_rewrite module or equivalent

Compatible Hosts

Sign in

Login details