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

时间:2016-02-26 07:52:39

标签: sitecore glass-mapper

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

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

  1. 获取上下文项
  2. 如果上下文项具有特定模板,则可以
  3. 如果它有不同的模板,则使用该模板查找另一个项目 根据一些业务规则,也检查模板
  4. 我想使用SitecoreContext类,如下所述: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的基本功能。

    我只能考虑使用某种棘手的查询,而且我没有找到关于其他可能性的文档。

2 个答案:

答案 0 :(得分:7)

您还可以将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代码生成模板。

答案 1 :(得分:1)

您可以尝试使用:

[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相匹配。如果是,则返回映射项,否则跳过它。