Search

I’m working on a bit of XSLT for a new site and I need to test whether or not we’re on the last node.

The idea is I’m concatenating a list of authors from a node list and so far I can’t seem to get it to behave.

Here’s my XSLT:

<xsl:for-each select="presenter/item">
    <xsl:choose>
        <xsl:when test="last()">
            <xsl:text> and </xsl:text><xsl:value-of select="."/>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="."/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:for-each>

The problem is that every node seems to think it’s the last one.

Also, similarly, if there is a way to test if it is the first that would be great as well.

I think you need to test position() = last() or position() = first() 1.

I believe there is no such thing as first() as it’s always equal to 1. :-)

Hmm, that didn’t seem to do it.

I’ll keep poking around.

I usually do something like:

 <xsl:for-each select="presenter/item">
     <xsl:choose>
         <xsl:when test="position() = count(/path/to/presenter/item)">
             <xsl:text> and </xsl:text><xsl:value-of select="."/>
         </xsl:when>
         <xsl:otherwise>
             <xsl:value-of select="."/>
         </xsl:otherwise>
     </xsl:choose>
 </xsl:for-each>

@phoque: Of course, you’re right - has been a long day :)

Huh. I have no idea what I changed but I just rewrote that bit of code from scratch as per Nils’ and Phoque’s instructions and it works just fine now.

Thanks for the assist!

<xsl:template match="presenter/item">
    <xsl:choose>
        <xsl:when test="position() != (last()-1) and position() != last()">
            <xsl:value-of select="."/><xsl:text>, </xsl:text>
        </xsl:when>
        <xsl:when test="position() = last()-1">
            <xsl:value-of select="."/><xsl:text>, and </xsl:text>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="."/><xsl:text>.</xsl:text>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

Should return presenter 1, presenter 2, presenter N, and presenter N+1.

position()=1 or position()=last()

Yeah, that’s what I ended up going with. It allowed me to add an “anything else” clause to the choose. Now it works as required.

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