Get Random Item from XSLT Rendering


Had a request to write an XSLT Extensions that can select a random child of an Item.  I wrote this extension that takes in a Sitecore Query and randomly selects one of the times. You could use it to do something like randomly display a Teaser from a Teaser Folder.

After compiling the code you will have to register the XSLT extension in your web.config file and add the namespace to the top of your XSLT Transformation.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sitecore.Xml.Xsl;
using Sitecore.Data.Items;
using System.Xml.XPath;
using Sitecore.Configuration;
using Sitecore.Xml.XPath;

namespace Sitecore.Prototypes.Client.Xslt
{
    public class Extensions : XslHelper
    {
        private static readonly XPathNavigator emptyNavigator;
        private static Random randomInstance = new Random();

        public XPathNodeIterator GetRandomResult(string query)
        {
            Item[] items = Sitecore.Context.Database.SelectItems(query);
            if (items != null)
            {
                int skip = randomInstance.Next(items.Count());
                try
                {
                    Item item = items[skip];
                    if (item == null)
                    {
                        return CreateEmptyIterator();
                    }
                    ItemNavigator navigator = Factory.CreateItemNavigator(item);
                    if (navigator == null)
                    {
                        return CreateEmptyIterator();
                    }
                    return navigator.Select(".");

                }
                catch (Exception e)
                {
                    Sitecore.Diagnostics.Log.Fatal(e.Message, this);
                }
            }
            return null;
        }
        private XPathNodeIterator CreateEmptyIterator()
        {
            return emptyNavigator.Select("*");

        }
    }
}

Advertisements

About Kevin Buckley
.Net web developer with a lot of experience in CMS. Currently working at Sitecore as Solutions Engineer.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: