2
votes

I'm trying to find all templates that inherit a particular template through code. I have the ID of the base template (Base Web Page), and I'm iterating through all of the template items in Sitecore looking for items that inherit Base Web Page.

foreach (var item in templateItems)
{
    var baseTemplates = item.Template.BaseTemplates.ToList();
    foreach (var baseTemplate in baseTemplates)
    {
        if (baseTemplate.ID == templateItem.ID)
        {
            inheritors.Add(item.ID.ToString());
        }
    }
}

However, item.Template.BaseTemplates gives me a list of the root level base templates; instead of giving me Base Web Page, it gives me the templates that Base Web Page inherits from (Advanced, Appearance, Help, etc)

enter image description here

Therefore I don't know if the item is actually inheriting Base Web Page or not.

Is there a method to get directly inherited templates? How can I find all templates that inherit Base Web Page?

1
Your solution lies in the LinkDatabase - Mark Cassidy
care to elaborate? - Erica Stockwell-Alpert

1 Answers

3
votes

The part item.Template in the

var baseTemplates = item.Template.BaseTemplates.ToList();

line is incorrect.

item.Template returns /sitecore/templates/System/Templates/Template here, so you're checking for a BaseTemplate of Template template always.

Your code should be:

foreach (var item in templateItems)
{
    var baseTemplates = new TemplateItem(item).BaseTemplates.ToList();
    foreach (var baseTemplate in baseTemplates)
    {
        if (baseTemplate.ID == templateItem.ID)
        {
            inheritors.Add(item.ID.ToString());
        }
    }
}

And the better approach may be using LinkDatabase to find all the referrers of your item which link from BaseTemplate field like that:

var links = Sitecore.Globals.LinkDatabase.GetItemReferrers(templateItem, false);
foreach (var link in links)
{
    if (link.SourceFieldID == Sitecore.FieldIDs.BaseTemplate)
    {
        inheritors.Add(link.SourceItemID.ToString());
    }
}