Get data source items from renderings in a placeholder

Get data source items from renderings in a placeholder

I was recently in a situation where I needed to look at the data source items of all the renderings added to a specific placeholder.

Luckily not too long ago I made some extension methods to get the number of renderings in a placeholder, which made the this pretty simple.

All I had to do was to modify those methods to return the actual renderings instead of just the count. Then for each of them go and get the item set in the property Settings.DataSource of the rendering reference (this is an ID stored as a string).

public static IList<Item> GetDataSourcesInDynamicPlaceholder(this Item item, string placeholder)
{
    var renderings = item.GetRenderingsInDynamicPlaceholder(placeholder);
    return GetDataSourceItemsFromRenderings(renderings, item.Database);
}

public static IList<Item> GetDataSourcesInPlaceholder(this Item item, string placeholder)
{
    var renderings = item.GetRenderingsInPlaceholder(placeholder);
    return GetDataSourceItemsFromRenderings(renderings, item.Database);
}

private static IList<Item> GetDataSourceItemsFromRenderings(IEnumerable<RenderingReference> renderings, Database database)
{
    return renderings.Where(x => x.Settings.DataSource?.Length > 0)
                     .Select(x => database.GetItem(x.Settings.DataSource))
                     .ToList();
}

Below are the modified versions of the extension methods from my other post, which now returns the actual renderings in a placeholder.

For dynamic placeholders this is assuming you are using the probably most common way of handling this – by adding a unique GUID to the placeholder name.

public static IList<RenderingReference> GetRenderingsInDynamicPlaceholder(this Item item, string placeholder)
{
    var regex = new Regex($"/{placeholder}" + @"_\w{8}(?:-\w{4}){3}-\w{12}$", RegexOptions.IgnoreCase);
    var renderingReferences = item.Visualization.GetRenderings(Sitecore.Context.Device, true);
    var renderingsInPlaceholder = renderingReferences.Where(r => regex.IsMatch(r.Placeholder));
    return renderingsInPlaceholder.ToList();
}

public static IList<RenderingReference> GetRenderingsInPlaceholder(this Item item, string placeholder)
{
    var renderingReferences = item.Visualization.GetRenderings(Sitecore.Context.Device, true);
    var renderingsInPlaceholder = renderingReferences.Where(r => r.Placeholder.EndsWith("/" + placeholder));
    return renderingsInPlaceholder.ToList();
}