Skip to content

Create custom tokens for the content editor

Posted in :

rbatallas

Sometimes we have to use custom tokens in the standard values to accomplish the requirement, in this article, we are going to create a new variable replacer to add our custom tokens

Let’s follow up on these next steps to do it.

In your project, create a new replacer class is my case with this name: CustomMasterVariablesReplacer

 public class CustomMasterVariablesReplacer
 { 

 }

Inherit the class from the base class named “MasterVariablesReplacer”

public class CustomMasterVariablesReplacer : MasterVariablesReplacer
{
    


}

Do an override to the method “ReplaceValues”

protected override string ReplaceValues(string text, Func<string> defaultName, Func<string> defaultId, Func<string> defaultParentName, Func<string> defaultParentId)
{
    return "";
}

Now, modify the method to execute the replacement of your new custom token, in a similar way to this

protected override string ReplaceValues(string text, Func<string> defaultName, Func<string> defaultId, Func<string> defaultParentName, Func<string> defaultParentId)
{
    Sitecore.Text.ReplacerContext context = GetContext();
    text = ReplaceWithDefault(text, "$timeHHmmss", () => DateTime.UtcNow.ToString("HHmmss"), context);
    text = base.ReplaceValues(text, defaultName, defaultId, defaultParentName, defaultParentId);
    return text;
}

I’m adding this new token “”$timeHHmmss”” to display the time as one value in the standard values of the template

the complete example looks like this

using Sitecore.Data;
using System;


namespace Example.Foundation.Common.Replacer
{
    public class CustomMasterVariablesReplacer : MasterVariablesReplacer
    {
        protected override string ReplaceValues(string text, Func<string> defaultName, Func<string> defaultId, Func<string> defaultParentName, Func<string> defaultParentId)
        {
            Sitecore.Text.ReplacerContext context = GetContext();
            text = ReplaceWithDefault(text, "$timeHHmmss", () => DateTime.UtcNow.ToString("HHmmss"), context);
            text = base.ReplaceValues(text, defaultName, defaultId, defaultParentName, defaultParentId);
            return text;
        }
    }
}

The final step is to add the patch file to activate the Replacer in our instance

<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:role="http://www.sitecore.net/xmlconfig/role/" xmlns:env="http://www.sitecore.net/xmlconfig/env/">
  <sitecore>
    <settings>
      <setting name="MasterVariablesReplacer">
        <patch:attribute name="value">Example.Foundation.Common.Replacer.CustomMasterVariablesReplacer,Example.Foundation.Common.dll</patch:attribute>
      </setting>
    </settings>
  </sitecore>
</configuration>

Now, use it in your standard values templates in this way

and the result shows up like this

And that is it.

Happy coding 😀