4

Is there a way to check the template ID of a Sitecore item with glass mapper?

My business logic would do the following:

  1. Get the context item
  2. If the context item has specific template it is OK
  3. If it has a different template, then find another item with that template according to some business rules which also check the template

I would like to use the SitecoreContext class, described here: http://www.glass.lu/Mapper/Sc/Documentation/ISitecoreContext

My code looks like this:

var context = new SitecoreContext(); 

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

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

return GetFallbackItem();

I don't really want to customize Glass Mapper for this, since it seems to me it should be a basic feature to check the template ID.

I can only think of using some kind of tricky query for this and I didn't find documentation about an other possibility.

Marek Musielak
  • 26,832
  • 8
  • 72
  • 80
Tamas Molnar
  • 797
  • 2
  • 9
  • 25

2 Answers2

7

You can also add the SitecoreInfoType.TemplateId attribute to a property on your model which Glass will then map to the TemplateID of the item.

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

You can then check the template id against your item

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

The solution from @Maras is cleaner but it depends on the set up of your templates and may depend on whether you are using Code Generation templates using TDS for example.

jammykam
  • 16,940
  • 2
  • 36
  • 71
  • Thanks. This actually also answers my original question, but I have decided to to use Marek's solution since it fits my use case better. – Tamas Molnar Feb 29 '16 at 14:26
1

You can try to use:

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

Here is the description of the EnforceTemplate property:

/// <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; }

With the EnforceTemplate property set Glass Mapper will check to see if the item being mapped matches the ID of the template defined by the SitecoreType attribute. If it does then it returns the mapped item otherwise it skips it.

Marek Musielak
  • 26,832
  • 8
  • 72
  • 80