Every now and again I find myself looking for a way to easily switch the Sitecore PageMode for a code block for either testing what happens when in specific modes or render renderings a specific way. The easiest solution is to use SetDisplayMode on the Context Site:
1 |
Sitecore.Context.Site?.SetDisplayMode(DisplayMode.Normal, DisplayModeDuration.Temporary); |
While this is very clean and simple, it often leads to repetitive code blocks. I wonder why Sitecore doesn’t provide a PageModeSwitcher as part of the out of the box API just like the ContextItemSwitcher, SiteContextSwitcher, or DatabaseSwitcher (any others to be honest).
Since a switcher is not available out of the box, we can create our own using the SetDisplayMode method and implement IDisposable:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
namespace Example { using System; using Sitecore.Sites; public sealed class PageModeSwitcher : IDisposable { /// <summary> /// The Desired Display Mode while in the context /// </summary> private readonly DisplayMode desiredMode; /// <summary> /// THe Previous Display Mode that will be transitioned out of the context to /// </summary> private readonly DisplayMode previousMode; /// <summary> /// Gets the Current DisplayMode /// </summary> private DisplayMode CurrentMode => Sitecore.Context.Site?.DisplayMode ?? DisplayMode.Normal; public PageModeSwitcher(DisplayMode desiredMode) { this.desiredMode = desiredMode; this.previousMode = Sitecore.Context.Site?.DisplayMode ?? DisplayMode.Normal; this.Enter(); } /// <summary> /// Enters the Desired Mode if not already within the Display Mode /// </summary> public void Enter() { if (this.CurrentMode != this.desiredMode) { Sitecore.Context.Site?.SetDisplayMode(this.desiredMode, DisplayModeDuration.Temporary); } } /// <summary> /// Exists the Desired Mode if not already within the Display Mode /// </summary> public void Exit() { if (this.CurrentMode != this.previousMode) { Sitecore.Context.Site.SetDisplayMode(this.previousMode, DisplayModeDuration.Remember); } } public void Dispose() { this.Exit(); } } } |
And to use, we simply do the following:
1 2 3 4 |
using (new PageModeSwitcher(DisplayMode.Edit)) { // Execute code as if the mode was in Experience Editor } |
Do you have any tips and tricks that you want to share? Comment below!