30Jul, 2024
Like All of Us, RenderingContext Is Changing, So Better Watch Out
As covered in my earlier article, The Road to Headless, I'm going through a number of Sitecore upgrades this year. Right now we're at phase 1, "Get to the latest version", where code is updated. For the most part there have been no gotchas in our coding, but this week one of our team members came across a RenderingContext issue that will be sure to catch some teams off guard.
According to Sitecore Support, there has been a change in behavior for the RenderingContext.Current.ContextItem property in Sitecore version 10.3, as part of a bug fix. Post Sitecore 10.3, the new behaviour for the RenderingContext.Current.ContextItemproperty is set to:
- The current rendering's datasource item (if non-null)
- The ancestor rendering's datasource item (if non-null)
- The page item
Applying the Correction
Here's the original code from our Abstractions project:
public IItem PageItem { get { if (_pageItem == null) { var pageItem = _renderingContext?.ContextItem; if (pageItem != null) _pageItem = new SitecoreItem(pageItem); } return _pageItem; } }
And here's the updated version. See it? The PageContext.Item is the change you'll want to note.
public IItem PageItem { get { if (_pageItem == null) { var pageItem = _renderingContext?.PageContext.Item; if (pageItem != null) _pageItem = new SitecoreItem(pageItem); } return _pageItem; } }