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.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xsl:stylesheet [ <!ENTITY nbsp "&#x00A0;"> ]>
    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); }

    <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 />

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