Contextualizing content type thumbnails in Optimizely CMS

Contextualizing content type thumbnails in Optimizely CMS

In the CMS when creating a block or a page a list of all the available content types will be displayed. Each content type can have its own custom thumbnail image to help identify what the content is used for. One common practice is to take a screenshot of the component as it was designed and use that as the thumbnail. To configure the thumbnail image you can add the ImageUrl attribute to any content type. The attribute has a parameter that can be used to set the path to the image.

Now I had a scenario where a block is used in multiple different sites — and each site has its own styling theme. If I were to use a screenshot of the block design then the styling will would be incorrect for all but one of the sites. This is because the thumbnail path can only be configured once per block type. To solve this I created a simple solution that enables a different thumbnail to be displayed for a block type based on the context. Note that for this example I'm only using block types, but it can be used for any content types.

The following snippet contains a custom attribute that inherits from the aforementioned ImageUrlAttribute and overrides the Path variable — in order to get the thumbnail path based on the name of the current site.

public class ContextualImageUrlAttribute : ImageUrlAttribute
{
    public ContextualImageUrlAttribute(string name) : base(string.Empty)
    {
        FileName = name;
    }

    public string FileName { get; }

    public override string Path => $"~/{SiteDefinition.Current.Name}/Thumbnails/" + FileName + ".jpg";
}

For this to work the thumbnails have to be stored inside folders that are named after each site. For example the path to a thumbnail for one site could be /MySite/Thumbnails/custom-block.jpg.

The new attribute can then be added to any content type. Here you can see it being used on a block.

[ContextualImageUrl("hero-banner-block")]
public class HeroBannerBlock : BlockData
{
}

This is a simple example of how you can use a custom attribute implementation to contextualize the thumbnail path. In other scenario's you may want to change the path based on a configurable setting or some other contextual property. Hopefully this example can help developers make the editing experience more user friendly in a similar multi-site solution.