I am using sitecore 7.2 & I have created pipeline for enclosing tags for single-line Text as below.
public class SingleLineFieldEnclosingTags
{
public void Process(RenderFieldArgs args)
{
if (args.FieldTypeKey != "single-line text" && args.FieldTypeKey != "multi-line text")
return;
args.Result.FirstPart = Helper.WrapInTags(args);
}
}
public static string WrapInTags(RenderFieldArgs args)
{
string keyInParam = args.Parameters.Where(x => x.Key.Contains("enclosingTag")).FirstOrDefault().Key;
string wrappedText = args.Result.FirstPart;
if (IsPageEditorMode)
{
return wrappedText;
}
if (keyInParam != null && keyInParam.Trim().Equals("enclosingTag"))
{
if (args.Parameters.ContainsKey(keyInParam))
{
string[] paramTags = args.Parameters[keyInParam].Split('|').Reverse().ToArray();
foreach (string tag in paramTags)
{
wrappedText = string.Concat("<", tag.Trim(), ">", wrappedText, "</", tag.Trim().Split(' ')[0], ">");
}
if (wrappedText.Contains("enclosingTag"))
{
// remove enclosing tag attribute from tags
wrappedText = Regex.Replace(wrappedText, @"enclosingTag\s*=\""\s*?.*\""", string.Empty, RegexOptions.IgnoreCase);
}
return wrappedText;
}
}
return wrappedText;
}
It is working fine, but problem comes when we edit or save any field then it save it as
<p class="intro">Do you need something specific?</p>
including enclosing tags too. and now in publish mode it display twice, thrice and so one like below.
<p class="intro"></p>
<p class="intro"></p>
<p class="intro"></p>
<p class="intro">Do you need something specific?</p>
<p></p>
<p></p>
<p></p>
I presume you have added this pipeline to
Item:Saved. As you have found, publishing actually also creates/saves the item in the web database, the same event is fired on that server and hence the reason you are seeing the repeated tags. Add a check to make sure you are running in the master database in yourprocessmethod:However, you may want to check if your text is already wrapped in the tag you are enclosing in (as well) - use HTMLAgilityPack or CsQuery instead of messing with regular expressions. In a simple scenario such as a
single-line textfield you could probably just get away with aStartsWith()check instead.You should consider moving your code to the
renderFieldpipeline instead (more info in this blog post or this one), or make use of theEnclosingTagattribute of theFieldRenderer. This way the tags are added at render time, rather than appearing in the content editor. There is some code in this SO answer I posted previously that you can use to pass the css class as well.