Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 345
Tamas Molnar Avatar asked Feb 08 '23 15:02

Tamas Molnar


1 Answers

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.

like image 80
jammykam Avatar answered Mar 15 '23 23:03

jammykam