Tuesday, September 19, 2017

Template inheritors

Hi there!

Today I am going to show you how you can quickly get inheritors of specific template. Let's imagine situation when you have base template, for instance _ProductBase and some templates which inherit from this one, let's say ProductA, ProductB, ProductC. We know that all future product templates
will also have _ProductBase in theirs base templates. In case when you will need get all product types available in project(and it is really probable :)), this solution will fit very well to this need.

Let's look to code. I've prepared it as the extension to TemplateItem.

public static class TemplateExtensions
    {
        /// <summary>
        /// Gets template inheritors 
        /// </summary>
        /// <param name="template"></param>
        /// <returns></returns>
        public static ICollection<string> GetTemplateInheritors(this TemplateItem template)
        {
            if (template != null)
            {
                var inheritors = Globals.LinkDatabase.GetReferrers(template)
                    .Where(l => l.GetSourceItem().Paths.FullPath.StartsWith("/sitecore/templates/") 
                    &&!l.GetSourceItem().Paths.FullPath.StartsWith("/sitecore/templates/system"))                   
                    .Select(l => l.SourceItemID.ToString())
                    .ToList();

                return inheritors;
            }
            return new List<string>();
        }
    }

It is important to take only items from templates root and exclude paths with standard Sitecore templates, it is /sitecore/templates/system, because we will not need this here.

I hope that you're enjoyed by this short post. Thank you for your time and stay tuned!


Share:

0 comments:

Post a Comment