An Independent Sitecore Learning Resource

Menu

Get the Base Templates of an Item with PowerShell

Get the Base Templates of an Item with PowerShell

Author

Brandon Bruno

Published

4/26/2017

Tags

Using the TemplateManager Class

Template inheritance is one of Sitecore's most powerful concepts. Addressing items based on their template is a great way to query for or compare similar content.

In a recent task, I had to compare items based on their templates - in this case, it was the base template that I cared about. My tool of choice was Sitecore PowerShell Extensions (SPE).

SPE has access to the full Sitecore API, so retreiving an item's base template is a breeze using the TemplateManager class:

		
# Get an item
$item = Get-Item -Path master:// -ID “{b94d8408-4833-4e4e-83da-b109f06967af}”

# Get the direct template for the item, then get all base templates of that template
$baseTemplates = [Sitecore.Data.Managers.TemplateManager]::GetTemplate($item).GetBaseTemplates();

# Just for show
foreach ($template in $baseTemplates) {
	echo $template.Name
}
	

Because templates support multiple inheritence, there may be more than one base template to be concerned about - or even multiple layers of base templates. If you want to know whether or not a certain template is used by an item - no matter what its level of inheritence - the InheritsFrom() method (on the Template object) is your friend:

	
# Get an item
$item = Get-Item -Path master:// -ID “{b94d8408-4833-4e4e-83da-b109f06967af}”

# Get the direct template for the item, then check to see if it has a certain base template based on the template's ID
$hasTemplate = [Sitecore.Data.Managers.TemplateManager]::GetTemplate($item).InheritsFrom(“{1b1931fa-72f2-42ee-ac24-f6c9583f4eb6}”);

# Just for show
if ($hasTemplate) {
	echo "Yep, it has that template."
}
	

Do you have questions or comments about this post? Find me on Twitter: @SitecoreSpark