Getting the number of renderings within a placeholder

Getting the number of renderings within a placeholder

Sometimes you might want to do something if there are no renderings in a placeholder or if there is a specific amount. You might want to show editors a warning or some help text if there are no renderings.

Unfortunately there is not a simple out-of-the-box way to do this in Sitecore, but it is somewhat trivial to do yourself.

I ended up with these two extension methods – one for default placeholders and one for dynamic placeholders which many (if not most) solutions use.

public static int RenderingsInDynamicPlaceholder(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.Count();
}

public static int RenderingsInPlaceholder(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.Count();
}

These might not work in 100% of cases, but they should work in most. You could make the GUID-regex for the dynamic placeholder more explicit, but I don’t see any practical need for it.

The methods basically run through all renderings and check their placeholder to see if it ends with the one we’ere looking for. In the case of the dynamic placeholders we need to use regex as they have a dynamically generated GUID appended to the placeholder name.