问题
I am trying to create a custom token where, if a user inputs certain text in a rich text editor field, that text will display a value. So say the user inputs @@tester like, "Todays month is @@tester" in a rich text editor field. I have c# trying to find @@tester in any rich text editor field within sitecore, and if it finds that token to find that token in a title field that matches where the text is to be replaced. So ie:
Item Name = token
Item ID = {06912058-6U9A-4BBF-BAE3-9306974EBE68}
Title = @@tester
Content (rich text editor) = February
I have so far:
namespace LonzaWeb.Pipeline.RenderField
{
public class AddToken
{
public void Process(RenderFieldArgs args)
{
Item currentItem = Sitecore.Context.Item;
if ((args.FieldTypeKey == "rich text") && currentItem.TemplateID.ToString() == "{06912058-6U9A-4BBF-BAE3-9306974EBE68}")
{
var tItem = currentItem.Fields["Title"].ToString();
if (tItem != null) {
Regex regex = new Regex(tItem);
Match match = regex.Match(tItem);
}
}
}
}
}
Also I am trying to use RegEx pattern matching. I have added this into the webconfig file to make sure it looks for it.
回答1:
Extending the <renderField> pipeline is probably a better way to go.
A new type can be provided with its own Process method. The type of the field being processed can be checked with the RenderFieldArgs.FieldTypeKey. The FieldValue property can be updated with values for each supported token.
Each processor in the pipeline will pass the resulting args to the next processor in line. I would add this patch after GetTextFieldValue.
http://www.sitecore.net/learn/blogs/technical-blogs/sitecorebetter/posts/2013/06/extending-the-sitecore-renderfield-pipeline.aspx
http://www.sitecore.net/learn/blogs/technical-blogs/john-west-sitecore-blog/posts/2011/08/replace-tokens-in-rich-text-fields-using-the-sitecore-aspnet-cms.aspx
回答2:
Since you are going to render the rich text value on the Live site, you can do the replacement on Page Load. The below method can be a centralized one, so any other sublayouts that requires Rich Text Replacement can use it
public static string RichTextReplacer(Item currentItem, string fieldName)
{
var richTextValue = currentItem.Fields[fieldName].Value;
var getToken = Sitecore.Context.Database.Items.GetItem("path to your token item");
var sb = new StringBuilder(richTextValue);
sb.Replace(getToken.Fields["Title"].value, getToken.Fields.["Content"].value);
return sb.ToString();
}
You can use the method as centralize and you just need to pass the different parameters that are required. You may add / remove parameters that suit your needs
来源:https://stackoverflow.com/questions/36701532/how-to-create-a-custom-token-in-sitecore