このコードを使用して、Item を特定のタイプの Glass モデルとしてロードできるかどうかを判断しました。例として IRateableItem タイプを使用しました。
public void Main()
{
var item = Sitecore.Context.Item;
if (item.TemplateID.Equals(GetSitecoreTypeTemplateId<IRateableItem>()))
{
// item is of the IRateableItem type
}
}
private ID GetSitecoreTypeTemplateId<T>() where T : class
{
// Get the GlassMapper context
var context = GetGlassContext();
// Retrieve the SitecoreTypeConfiguration for type T
var sitecoreClass = context[typeof(T)] as SitecoreTypeConfiguration;
return sitecoreClass.TemplateId;
}
private SitecoreService GetSitecoreService()
{
return new SitecoreService(global::Sitecore.Context.Database);
}
private Glass.Mapper.Context GetGlassContext()
{
return GetSitecoreService().GlassContext;
}
編集:
この拡張メソッドを追加して、テンプレートが特定の基本テンプレートから継承されているかどうかを判断できるようにします。
public static bool InheritsFrom(this TemplateItem templateItem, ID templateId)
{
if (templateItem.ID == templateId)
{
return true;
}
foreach (var template in templateItem.BaseTemplates)
{
if (template.ID == templateId)
{
return true;
}
if (template.InheritsFrom(templateId))
{
return true;
}
}
return false;
}
だから今、あなたはこれを行うことができます:
if (item.Template.InheritsFrom(GetSitecoreTypeTemplateId<IRateableItem>()))
{
// item is of type IRateableItem
}