Thursday, January 15, 2009

Show Alternating Rows in Content Query Web Part

Often you need to display alternating rows in a Content Query Web Part (CQWP), so that for example you get a record on a white background, then a record on a gray background, then on white again etc. Yes, you can create a special “index” column in your source content type and based on its value determine if a given row is odd or even.

There is a better way however: from within your ItemStyleTemplate.xsl you can know the position of the current node, which you can always translate into the knowledge of whether the current row is odd or even:

<xsl:template name="AlternatingItems" match="Row[@Style='AlternatingItems']" mode="itemstyle">
<xsl:variable name="CurPosition" select="count(./preceding-sibling::*)" />
<xsl:variable name="AlternatingCssClass">
<xsl:choose>
<xsl:when test="($CurPosition mod 2 = 0)">
<xsl:value-of select="'CssClassAlt1'" />
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="'CssClassAlt2'" />
</xsl:otherwise>
</xsl:choose>
</xsl:variable>
… the rest of the template

On a related but different topic, in order to have a field exposed to your XSL file as an attribute of the Row XML element you typically need to export the CQWP to a file then edit its property named CommonViewFields as perfectly explained by Heather Solomon here.

The only thing calling for some expansion after reading this blog post is how to know which field name and which type name exactly to feed into the CommonViewFields property. The definitive source of the information about which fields are there and which are their types is located in here:

%ProgramFiles%\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES\fields\fieldswss.xml

Each field in this XML file has a Name attribute and a Type attribute, their values can be fed into the CommonViewFields property of your CQWP. Ideally we want to be able to list all applicable fields based on currently selected options for the query, but this would require extending the web part itself…

3 comments:

  1. With regards to field types: there are more of these for the publishing sites. They are located in here:
    %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES\PublishingResources\PublishingColumns.xml

    ReplyDelete
  2. Thanks for the post worked like a charm

    ReplyDelete
  3. Excellent - many thanks for posting this. I could manage the XSL OK but I couldn't figure out the XPath to set the CurPosition. I find it hard to figure out XPath syntax so this post helped me to put that piece in.

    ReplyDelete