Skip to content

Instantly share code, notes, and snippets.

@phaniav
Created September 17, 2017 18:46
Show Gist options
  • Save phaniav/8782fddc9d32a8bb2378c13321c8da79 to your computer and use it in GitHub Desktop.
Save phaniav/8782fddc9d32a8bb2378c13321c8da79 to your computer and use it in GitHub Desktop.
Custom Sitecore Tokens and replacement
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<settings>
<setting name="MasterVariablesReplacer">
<patch:attribute name="value">Sitecore.Sharedsource.Data.MasterVariablesReplacer,Sitecore.Sharedsource</patch:attribute>
</setting>
</settings>
</sitecore>
</configuration>
namespace Sitecore.Sharedsource.Data
{
using System;
using System.Collections.Generic;
using SC = Sitecore;
public class MasterVariablesReplacer : SC.Data.MasterVariablesReplacer
{
public override string Replace(string text, SC.Data.Items.Item targetItem)
{
SC.Diagnostics.Assert.ArgumentNotNull(text, "text");
SC.Diagnostics.Assert.ArgumentNotNull(targetItem, "targetItem");
string result = this.ReplaceValues(
text,
() => targetItem.Name,
() => targetItem.ID.ToString(),
() => SC.Data.Items.ItemUtil.GetParentName(targetItem),
() => targetItem.ParentID.ToString());
return result;
}
private string ReplaceValues(
string text,
Func<string> defaultName,
Func<string> defaultId,
Func<string> defaultParentName,
Func<string> defaultParentId)
{
if ((text.Length != 0) && (text.IndexOf('$') >= 0))
{
SC.Text.ReplacerContext context = this.GetContext();
if (context != null)
{
foreach (KeyValuePair<string, string> pair in context.Values)
{
text = text.Replace(pair.Key, pair.Value);
}
}
text = this.ReplaceWithDefault(text, "$name", defaultName, context);
text = this.ReplaceWithDefault(text, "$id", defaultId, context);
text = this.ReplaceWithDefault(text, "$parentid", defaultParentId, context);
text = this.ReplaceWithDefault(text, "$parentname", defaultParentName, context);
text = this.ReplaceWithDefault(text, "$date", () => SC.DateUtil.IsoNowDate, context);
text = this.ReplaceWithDefault(text, "$time", () => SC.DateUtil.IsoNowTime, context);
text = this.ReplaceWithDefault(text, "$now", () => SC.DateUtil.IsoNow, context);
text = this.ReplaceWithDefault(text, "$user", () => SC.Context.User.LocalName, context);
}
return text;
}
private string ReplaceWithDefault(
string text,
string variable,
Func<string> defaultValue,
SC.Text.ReplacerContext context)
{
if ((context != null) && context.Values.ContainsKey(variable))
{
return text;
}
if (text.IndexOf(variable, StringComparison.InvariantCulture) < 0)
{
return text;
}
return text.Replace(variable, defaultValue());
}
}
}
@phaniav
Copy link
Author

phaniav commented Sep 17, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment