You can use Scriban extension
as below to fetch random list of children from datasource item.
- Create the
Scriban Extension
as below, to generate the random list that take list of items and the number of items to be returned as a parameter.
using Scriban.Runtime;
using Sitecore.Collections;
using Sitecore.Data.Items;
using Sitecore.XA.Foundation.Scriban.Pipelines.GenerateScribanContext;
using System;
using System.Collections.Generic;
using System.Linq;
public class GetRandomItemsFunction : IGenerateScribanContextProcessor
{
private delegate List<Item> RandomItemDelegate(ChildList item, int randomElementsListSize);
public void Process(GenerateScribanContextPipelineArgs args)
{
var randomItemsDelegate = new RandomItemDelegate(GetRandomItems);
args.GlobalScriptObject.Import("sc_random_items", (Delegate)randomItemsDelegate);
}
public List<Item> GetRandomItems(ChildList items, int randomElementsListSize)
{
if (items != null)
{
return items.OrderBy(x => Guid.NewGuid()).Take(randomElementsListSize).ToList();
}
return null;
}
}
- Thereafter, register the above
Scriban Extension
through below configuration patch:
<?xml version="1.0"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:set="http://www.sitecore.net/xmlconfig/set/" xmlns:role="http://www.sitecore.net/xmlconfig/role/">
<sitecore>
<pipelines>
<generateScribanContext>
<processor type="SitecoreCustomExtensions.ScribanExtensions.GetRandomItemsFunction,SitecoreCustomExtensions" resolve="true"/>
</generateScribanContext>
</pipelines>
</sitecore>
</configuration>
- Finally inside the Scriban, call the above
Scriban Extension
as below, with the datasource children and size i.e 3 as an argument to that extension.
{{randomList = sc_random_items i_datasource.children 3}}
{{if randomList}}
{{ for i_child_res in randomList }}
<p>{{i_child_res.Title.raw}}</p>
{{ end}}
{{ end}}
Using above changes, you can randomly fetch N number of items
from the list.
Hope this helps!!! Let me know in case you face any issues.