2017-09-11

Adding nicer icons to the PageTree in EPiServer

I did some research about adding nicer icons for pages in the EPiServer Page Tree, and I came up with some nice resources.

What seems to be common for all approaches is that you must create css-classes that encapsule each icon to use. At the moment I don't see how to get around this without actually creating the classes.

You also need to create an InitializableModule which sets up the icons when the web is started. I have omitted that code here. Please read the example from the first example below (from blog.nansen.com), for that code.

This example is complete and shows how to use your own (or a third party lib) icons:
http://blog.nansen.com/2014/10/page-tree-icons-in-episerver-cms-75.html

This example shows how to create your own icons (as an image sprite) and use for the icons: https://jonika.nu/JonasBlogg/archives/347


Here's one that shows how to use the already included icons from EPiServer:
https://ericceric.ghost.io/use-episervers-content-icons-as-site-tree-icons/

In stead of creating and maintaining the list of Episerver icons yourself, as in the example above, you could go for the Jon D Jones nuget package: https://www.nuget.org/packages/JonDJones.IconPack/. This iconpack does not really contain any icons, just convenience constants that point to the built-in episerver icons (it seems so to me anyway).


I created a generic attribute, based on reflection, that plugs in the JonDJones icon pack (download from Nuget, as mentioned) into the first example I mentioned from the "nansenblog":

[AttributeUsage(AttributeTargets.Class)]
public class ContentIconAttribute : Attribute
{
    public ContentIconAttribute(Type type, string propertyName)
    {
        IconClass = GetStaticStringValueFromLib(type, propertyName);
    }

    private string GetStaticStringValueFromLib(Type libType, string name)
    {
        var fieldInfo = libType.GetField(name);
        var propInfo = libType.GetProperty(name);
        var value = (fieldInfo?.GetValue(null) ?? propInfo?.GetValue(null)) as string;
        return value;
    }

    /// 
    /// Css class to apply to the icon
    /// 
    public string IconClass { get; set; }
}

And here's how to use it:
using JonDJones.IconPack;

[ContentIcon(typeof(ObjectIcons), nameof(ObjectIcons.Start))]
public class StartPageModel : BasePage
{
    ...
}