- Content Query Web Part
- Data View Web Part
- Search Core Results Web Part
- For guidance in setting up a Content Query Web Part, see this guide from Heather Solomon.
- For guidance setting up a Data View Web Part, see this guide by Laura Rogers.
<xsl:stylesheet version=”1.0″ exclude-result-prefixes=”x d ddwrt cmswrt xsl msxsl” xmlns:x=”http://www.w3.org/2001/XMLSchema” xmlns:d=”http://schemas.microsoft.com/sharepoint/dsp” xmlns:ddwrt=”http://schemas.microsoft.com/WebParts/v2/DataView/runtime” xmlns:cmswrt=”http://schemas.microsoft.com/WebParts/v3/Publishing/runtime” xmlns:xsl=”http://www.w3.org/1999/XSL/Transform” xmlns:msxsl=”urn:schemas-microsoft-com:xslt”>
The “Randomize” Template
Once the DDWRT namespace has been added, the ddwrt:Random function will be usable. It accepts two parameters: a minimum number and a maximum number. We’ll be using that in a custom template to choose results.
Here’s the core template to add to your XSL:
<xsl:templatename=“Randomize“>
<xsl:paramname=“Rows“ />
<xsl:paramname=“Limit“ />
<xsl:variablename=“SelectedRow“select=“ddwrt:Random(1, count($Rows))“ />
<xsl:value-ofselect=“$Rows[position() = number($SelectedRow)]/@FileLeafRef“ /><br/>
<xsl:iftest=“count($Rows) > 1 and ($Limit > 1 or $Limit = 0)“>
<xsl:call-templatename=“Randomize“>
<xsl:with-paramname=“Rows“select=“$Rows[position() != number($SelectedRow)]“ />
<xsl:with-paramname=“Limit“select=“$Limit – 1“ />
</xsl:call-template>
</xsl:if>
</xsl:template>
That template accepts two parameters.
- Rows: The node set of items to choose from.
- Limit: The number of items to return. To return everything, pass 0.
It works by selecting one node at a time, then iterating through the remaining nodes one at a time until either there are no nodes left or the limit has been met. Because of the recursive approach, overall running time is bound by O(N^2) where N is the number of nodes.
Randomizing Results
Once that template has been added, you can replace existing xsl:for-each loops with the following:
<xsl:call-templatename=“Randomize“>
<xsl:with-paramname=“Rows“select=“/dsQueryResponse/Rows/Row“/>
<xsl:with-paramname=“Limit“select=“1“/>
</xsl:call-template>