Adding Tokens in Sitecore

While there is a way to add tokens in fields using SXA, if you aren’t using SXA, you could use this strategy.

The use case for this example this. The client wants to add a <WBR> tag anywhere in their text. For certain languages, this can be important, as it lets the browser know that if you need to break, here the spots to do so. To do this, we’ll need to add a new render field pipelline processor.

using Sitecore.Diagnostics;
using Sitecore.Pipelines.RenderField;
using Sitecore.StringExtensions;

namespace SampleSite.Foundation.Base.PipelineProcessors.RenderField
{
    public class ProcessTokens
    {
        public void Process(RenderFieldArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            Assert.ArgumentNotNull(args.Item, "args.Item");
            Assert.ArgumentNotNull(args.GetField(), "args.GetField()");

            if (args.GetField().Value.Contains("{{wbr}}"))
            {
                args.Result.FirstPart = args.Result.FirstPart.Replace("{{wbr}}", "<wbr>");
            }
        }
    }
}

In our case, we made a rule for the authors, whenver you want to add in a <WBR> tag, use this token {{WBR}}. Each field that Sitecore renders will be send through this processor. This will example the contents of the field and perform the replacement.

This is required for Single Line Text fields and Link Descriptions. Rich text fields will process here as well, so the authors have a choice if the want to modify the html directly in that field or simple use the token.

One thing to note on this is that this worn’t work in Sitecore JSS as the fields don’t go through the field rendering pipelines in JSS. That has to be handled by your view code.

You can imagine modifying this code to be able to handle a set of tokens, and look up the proper values from an authorable Sitecore list.

Hope this helps.

About Phil Paris

Hi, my name is Phil Paris and I’m a Sitecore Architect and general Sitecore enthusiast. I’ve been working with Sitecore since 2013. Through this blog I will be sharing Sitecore insights, tips and tricks, best practices and general knowledge with the hopes to further the community at large. Please feel free to reach out to me at any time!

View all posts by Phil Paris →