【问题标题】:How to get template ID of an item with glass.mapper?如何使用 glass.mapper 获取项目的模板 ID?
【发布时间】:2016-02-26 07:52:39
【问题描述】:

有没有办法用玻璃映射器检查 Sitecore 项目的模板 ID?

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

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

我想使用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 应该是一项基本功能。

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

【问题讨论】:

    标签: sitecore glass-mapper


    【解决方案1】:

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

    【讨论】:

    • 谢谢。这实际上也回答了我最初的问题,但我决定使用 Marek 的解决方案,因为它更适合我的用例。
    【解决方案2】:

    你可以尝试使用:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-08
      • 1970-01-01
      相关资源
      最近更新 更多