This is the 6th article in my series about Episerver CMS display options. When we work with Episerver, we sometimes want to allow content editors to be able to dynamically set the width of a block on a page. This is what an Episerver display option will allow you to do. In the last guide, I wrote about how to limit the display options available to a content editor via a validation attribute. There is an alternative option to limiting what display options get rendered to the editor and that is to prevent Episerver from rendering the block.

The downside of this approach is that the content editor can add the block into a content area and save the page, however, they will see an error in the editor and the webpage won't contain the block. This approach MAY be useful if you want to create a settings block and you want to make sure it can never be rendered on a page. Think edge cases when considering this option. As each website is different I thought I'd share the code on how to do this more for knowledge sharing, in case anyone finds it useful.

A lot of this setup is based on the code within, How To Prevent Content Editors Adding Blocks With The Wrong Display Options.

The big difference is that instead of using the validation attribute, you would use this Initialization Module instead.

The Template Resolver Code

 

In the code above, if a display option exists and the page/block type inherits from an interface called IDisallowDisplayOptionthen prevent the render. Like the validation tutorial, I use an interface that defines a list of invalid display options. This interface contains no properties. It is just an easy way to add a tag onto the page type to use in this method 😎

The code checks if the block implements this interface, if it does, I get the display option tag associated with the request, convert it to a custom enum. You could use the string representation of the display option name here if you want to. I personally like the type of safety aspect of using an enum. I have not included the enum code, you could find an example here. The code then checks if the display option tag isn't on a banned list. The banned list is simply an array of enums that we do not want to render. If a match occurs we return null. When you return null back to Episerver it will display this error message within the editor:

How To Limit The Display Options Available To A Block Using The Template Resolver

There you have it, as you can see you can intercept requests made by the template resolver, determine which Episerver block/page triggered the request and then modify the SelectedTemplate property how you see fit. When you return null though, an error will be display in the Episerver editor. As mentioned above, the downside of this approach is that it doesn't stop the content editor from saving the page, if you want this sort of functionality using a validation attribute instead. Happy Coding 🤘