Sitecore get all base templates for an item recursively

5/21/2018 sitecore-templates

It's a good approach to divide all your Sitecore templates into small chunks. This helps re-usability of the templates.

What I normally do is create a template called "page" derived from a standard template and all my page templates will be derived from Page.

similarly, I create a template called "content" derived from a standard template and all content templates will be derived from the content template.

Sometimes we need to find out all the base templates associated with a single template.

This is how we can achieve this:

TemplateManager.GetTemplate(currentVersionToPublish)
                        .GetBaseTemplates()
                        .Any(template => template.ID == new ID("{TemplateIDTocompare}"));

GetBaseTemplates method will return all bases templates for the template recursively.

 public TemplateList GetBaseTemplates()
    {
      List<Template> result = new List<Template>();
      Set<ID> processed = new Set<ID>();
      this.AddBaseTemplates(result, true, processed);
      return new TemplateList((IEnumerable<Template>) result);
    }

2nd parameter true in AddBaseTemplate specifies deep.

Hope this helps.