2.16.2010

XSLT: Return a randomly ordered set of nodes [Umbraco]

FROM: http://forum.umbraco.org/yaf_postst5497_Get-x-number-of-uniquely-random-nodes.aspx#30603


We developed a simple solution for getting a randomly ordered set of nodes in the XSLT.

Using a random number seed, we sorted the node-set.

Code:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xsl:stylesheet [ <!ENTITY nbsp "&#x00A0;"> ]>
<xsl:stylesheet
    version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxml="urn:schemas-microsoft-com:xslt"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt"
    xmlns:lk="http://leekelleher.com"
    xmlns:umbraco.library="urn:umbraco.library"
    exclude-result-prefixes="msxml msxsl umbraco.library lk">
    <xsl:output method="xml" omit-xml-declaration="yes" />

    <xsl:param name="currentPage" />
    <xsl:variable name="maxItems" select="number(5)" />

    <msxsl:script language="JavaScript" implements-prefix="lk">
        function Random(r) { return Math.ceil(Math.random()*r); }
    </msxsl:script>

    <xsl:template match="/">

        <xsl:for-each select="$currentPage/node[string(data[@alias='umbracoNaviHide']) != '1']">
            <xsl:sort select="lk:Random($maxItems)" order="descending" />
            <xsl:if test="position() &lt;= $maxItems">
                <xsl:value-of select="@nodeName" /><br />
            </xsl:if>
        </xsl:for-each>
     
    </xsl:template>
</xsl:stylesheet>


The output will be unique, as we only randomised the sorting; as opposed to trying to access multiple random nodes.

The "maxItem" variable can be changed to take a macro parameter.

No comments:

Post a Comment