如何获取 glass.mapper 项的模板 ID?

How to get template ID of an item with glass.mapper?

有没有办法用 glass mapper 检查 Sitecore 项目的模板 ID?

我的业务逻辑将执行以下操作:

  1. 获取上下文项
  2. 如果上下文项有特定的模板就可以了
  3. 如果它有不同的模板,则使用该模板查找另一个项目 根据一些业务规则也检查模板

我想使用 SitecoreContext class,这里描述:http://www.glass.lu/Mapper/Sc/Documentation/ISitecoreContext

我的代码如下所示:

var context = new SitecoreContext(); 

var currentItem = context.GetCurrentItem<MyModel>();

if(HasCorrectTemplate(currentItem))
{
   return currentItem;
}

return GetFallbackItem();

我真的不想为此自定义 Glass Mapper,因为在我看来,检查模板 ID 应该是一个基本功能。

我只能想到为此使用某种棘手的查询,但我没有找到关于其他可能性的文档。

您可以尝试使用:

[SitecoreType(EnforceTemplate = SitecoreEnforceTemplate.Template, TemplateId = "{ID}")]
public class MyModel
{
    ...

这里是 EnforceTemplate 属性 的描述:

/// <summary>
/// Forces Glass to do a template check and only returns an class if the item
///             matches the template ID or inherits a template with the templateId
/// 
/// </summary>
public SitecoreEnforceTemplate EnforceTemplate { get; set; }

设置 EnforceTemplate 属性 后,Glass Mapper 将检查映射的项目是否与 SitecoreType 属性定义的模板 ID 匹配。如果是,那么它 returns 映射的项目,否则它会跳过它。

您还可以将 SitecoreInfoType.TemplateId 属性添加到模型上的 属性,然后 Glass 会将其映射到项目的 TemplateID。

//Returns the template ID of the item as type System.Guid.
[SitecoreInfo(SitecoreInfoType.TemplateId)]
public virtual Guid TemplateId{ get; set; }

然后您可以根据您的项目检查模板 ID

if(currentItem.TemplateId == {guid-of-template-to-match})
{
   return currentItem;
}

来自@Maras 的解决方案更清晰,但它取决于模板的设置,并且可能取决于您是否正在使用代码生成模板,例如使用 TDS。