Mental note: MaxItems with XSLT

Probably old news/code, but I couldn't find it when I went looking for it. I wanted to have an XSLT stylesheet that only displayed 'n' items from the source (in this case RSS). Here's the important bits:

The template:

  <xsl:template match="item">
  <xsl:param name="maxItems"/>
  <xsl:if test="count(preceding::item) &lt; $maxItems">
   <div id="itemWrapper">
    <xsl:if test="position() mod 2">
     <xsl:attribute name="id">itemWrapperHighlight</xsl:attribute>
    </xsl:if>
    <h3 id="itemTitle">
     <xsl:value-of select="title"/>
    </h3>
    <div id="itemBody">
     <xsl:value-of select="description"/>
     <br/>
     <a>
      <xsl:attribute name="href"><xsl:value-of select="url"/></xsl:attribute>
      <xsl:attribute name="alt"><xsl:value-of select="title"/></xsl:attribute>
   Read more of this item 
    </a>
    </div>
   </div>
  </xsl:if>
 </xsl:template>

The important bit in that is the line: . The "item" should be whatever expression is used to define the template. That is, "item" isn't a keyword in this case, but the RSS::item. I've seen a few other methods out there, but this seemed simpler than them.
The $maxItems is the parameter that will be provided when calling the template. The other item to notice here is the "alternating styles" using the position.


Calling the template:

   <xsl:apply-templates select="item">
    <xsl:with-param name="maxItems" select="6"/>
   </xsl:apply-templates>

This is from the channel template. It's a fairly normal apply-templates, but the parameter is assigned. Rather than have this hardcoded, you could pass this in using the XsltArgumentList collection when you're transforming.

As always, I'm assuming there is a better answer out there. Feel free to let me know.

Print | posted on Tuesday, July 25, 2006 11:15 PM

Feedback

# re: Mental note: MaxItems with XSLT

left by Anonymous at 7/25/2006 10:50 PM Gravatar
Kent,

You could use XPath position() function which returns integer value of the position of a node in a node set (1 for first node). I think fortunately it's an XPath 1.0 function.

# re: Mental note: MaxItems with XSLT

left by kent at 7/25/2006 11:58 PM Gravatar
Sure enough -- knew there had to be another solution. That one was just too easy. Thank you.
Comments have been closed on this topic.