Sitecore discovery of the month (year?) - Item.DescendsFrom
Hallelujah
That's what I thought when I found that since Sitecore 9.1 there is a built-in method in the Item
class that checks whether an item inherits from a given template - directly or, more importantly, indirectly.
This has always been an issue that many Sitecore developers faced. Something so simple yet so important was missing. A quick Google search results in several articles featuring the same or very similar minuscule extension method:
- https://blog.eldblom.dk/2011/12/07/inheritance-techniques-in-sitecore-asp-net-cms/
- https://community.sitecore.net/developers/f/8/t/8198
- https://blog.martinmiles.net/post/sitecore-item-extension-methods#IsDerived
- https://laubplusco.net/sitecore-extensions-does-a-sitecore-item-derive-from-a-template/
Then, suddenly, when starting a fresh Sitecore 9.3 project, I stumbled upon this beautiful tweet:
Could it really be? I quickly tried it out and it worked perfectly. I went to bed a happy man that day.
I pondered whether this small method deserved a blog post of its own, but I thought:
Hey, there are several posts on the old solution. The new one deserves at least one!
So here we are. To be totally honest, I did find a few mentions of it on the web besides that tweet and the linked post. One was a Habitat issue introducing Sitecore 9.1 support. Another one was a blog post on creating Header and Footer components where it was used without making a fuss like it was something completely normal. There was also a post about testing the content tree, where the method was mocked. And lastly, of all places, the method is mentioned in Helix documentation.
I was pretty curious as to how it was implemented, after all, I've seen at least a dozen community proposals and let's just say it is a familiar one 😉
Oh, snap! All this text and no mention of how to actually use this hot piece of code. Well, here is its signature in all its glory:
public virtual bool DescendsFrom(ID templateId)
That is in the Item
class, so use Item.DescendsFrom(ID templateId)
wherever you can!
Really simple, but beautiful. Huge shout-out to the Sitecore team for making it happen! 🎉