共用方式為


Howto: Select only unique values in the XSLT Data View Web Part

A lot of times you will want to display only unique values inside the Data View. What I have here is a variation of the Muenchian Method using an <xsl:key>. Check out jenitennison.com for a few variations on this.

First, browse out to your Announcements list (which you get by default when you create a SharePoint site), and add a few Announcements all with the same title (just for demonstrations sake :-))

Then...

1. Insert a Data View Web Part based on the Announcements list
2. Probably best to switch to code view at this point
3. Find the code that looks like this:
<xsl:template name="dvt_1.body">
<xsl:param name="Rows"/>
<xsl:param name="FirstRow"/>
<xsl:param name="LastRow"/>
<xsl:for-each select="$Rows">
<xsl:variable name="KeepItemsTogether" select="false()"/>
<xsl:variable name="HideGroupDetail" select="false()"/>
<xsl:variable name="GroupStyle" select="'auto'"/>
<xsl:if test="(position() &gt;= $FirstRow and position() &lt;= $LastRow) or $KeepItemsTogether">
<xsl:if test="not($HideGroupDetail)" ddwrt:cf_ignore="1">
<tr style="display:{$GroupStyle}">
<td class="ms-vb">
<xsl:value-of select="@Title"/>
</td>
<td class="ms-vb">
<xsl:value-of select="@Editor"/>
</td>
<td class="ms-vb">
<xsl:value-of select="ddwrt:FormatDate(string(@Modified), 1033, 5)"/>
</td>
</tr>
</xsl:if>
</xsl:if>
</xsl:for-each>
</xsl:template>
4. Change that code to look like this:
<xsl:template name="dvt_1.body">
<xsl:param name="Rows"/>
<xsl:param name="FirstRow"/>
<xsl:param name="LastRow"/>
<xsl:for-each select="$Rows">
<xsl:variable name="KeepItemsTogether" select="false()"/>
<xsl:variable name="HideGroupDetail" select="false()"/>
<xsl:variable name="GroupStyle" select="'auto'"/>
<xsl:variable name="uniqueTitle" select="@Title"/> <!-- this is added to create a variable containing the Title -->
<xsl:if test="(position() &gt;= $FirstRow and position() &lt;= $LastRow) or $KeepItemsTogether">
<xsl:if test="not($HideGroupDetail)" ddwrt:cf_ignore="1">
<tr style="display:{$GroupStyle}">
<td class="ms-vb"><!-- this next part is where we compare the variable created above to the current selection and if they are different, we write the value -->
<xsl:if test="generate-id()=generate-id(//Rows/Row[@Title=$uniqueTitle][1])">
<xsl:value-of select="@Title"/>
</xsl:if>
</td>
<td class="ms-vb">
<xsl:value-of select="@Editor"/>
</td>
<td class="ms-vb">
<xsl:value-of select="ddwrt:FormatDate(string(@Modified), 1033, 5)"/>
</td>
</tr>
</xsl:if>
</xsl:if>
</xsl:for-each>
</xsl:template>
5. Save the page. Notice that only the unique values are displayed. You can use this code in any number of places in the XSLT (for example, inside a drop-down menu).

Let me know what you think!

-John

Comments

  • Anonymous
    April 29, 2004
    Very nice! This one's in the toolkit :)