2016-02-26 59 views
4

有沒有辦法使用玻璃貼圖工具檢查Sitecore項目的模板ID?如何使用glass.mapper獲取項目的模板ID?

我的商業邏輯將執行以下操作:

  1. 獲取上下文項
  2. 如果上下文項目都有特定的模板就OK
  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(); 

我真的不希望自定義玻璃映射對於這一點,因爲在我看來,它應該是一個基本功能檢查模板ID。

我只能想到使用某種棘手的查詢爲此,我沒有找到有關其他可能性的文檔。

回答

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屬性設置玻璃映射器會檢查,如果該項目被映射匹配由SitecoreType屬性定義的模板的ID。如果確實如此,則會返回映射的項目,否則會跳過它。

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生成模板。

+0

謝謝。這實際上也回答了我原來的問題,但我決定使用Marek的解決方案,因爲它更適合我的用例。 – manipurea