Replace Custom tokens in RTE field with Some Values

I had a requirement from one of our clients, he was asking, if i have a keyword in RTE field in Sitecore, it is like a shared keyword will be used cross the site, so when i change it in one place, i need this keyword to be changed on other items that has this field as well, should i go through all of these items in Sitecore and change them one by one?

At that time I was thinking about number of items that he needs to go through, just to change that keyword , and in this post i will explain my proposed  solution for this.

  1. Define all the keywords, and adding them as items in Global folder in Sitecore, each keyword item will have Key and Value. so i will have lookup folder there with list of all common word that he needs :token1
  2. We will have custom tokens for that keyword for in the RTE Field, so i agreed with the client that we will have this inside brackets []:pallo
  3. Adding new processor after renderfield
public class RichTextTokens
 {
 private readonly ILookupRepository _lookupRepository;

public RichTextTokens(ILookupRepository lookupRepository)
 {
 _lookupRepository = lookupRepository;
 }

public virtual void Process(RenderFieldArgs args)
 {
 if (args.FieldTypeKey != "rich text")
 return;

if (Sitecore.Context.PageMode.IsPageEditorEditing)
 return;

Regex regex = new Regex(@"\[(.*?)\]");

var matches = regex.Matches(args.Result.FirstPart);

var matchesItems = (from Match match in matches select match.Value).ToList();

List<Item>  lookupItems;
 if (!HttpContext.Current.Items.Contains("Lookup-Cache"))
 {
  lookupItems=_lookupRepository.Search(matchesItems);
   HttpContext.Current.Items.Add("Lookup-Cache", lookupItems);
 }
 else
 {
 lookupItems = HttpContext.Current.Items["Lookup-Cache"] as List<Item>;
 }

if (lookupItems.Count > 0)
 {
 foreach (var lookupItem in lookupItems)
 {
 args.Result.FirstPart = args.Result.FirstPart.Replace(lookupItem.Key, lookupItem.Value);
 }
 }
 }
 }

Configurations:

<pipelines>
 <renderField>
 <processor patch:after="*[@type='Sitecore.Pipelines.RenderField.GetFieldValue, Sitecore.Kernel']" type="MySite.Pipelines.RichTextTokens, MySite"/>
 </renderField>
 </pipelines>

on the front-end site these tokens will be replaced with actual values from lookup repository.

I hope you find this post helpful, If you have any additional knowledge on this subject, comments or questions, please let me know in the comments section below.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s