This one will be a little short blog post, but this feature was very important in my latest project.

The design for the site was done by a front ender, who was doing a lot of <p>tags around texts. Also the <p> tag was styled to include some margin. When we implemented the design, and started rendering Rich Text fields, we ran into the inevitable problem that the design included a<p>-tag, and the Rich Text editor included a <p>-tag as well. This meant that the final markup would include two <p>-tags, giving us nested <p>-tags, and double styling!

The problem is that when you use the Rich Text editor, and write multiple lines, a line is done by encapsulating the text in a <p>-tag. This is pretty default, and correct html. The problem is that sometimes when the editor only writes one line of text, the text ISNT encapsulated in a tag. This makes it kind of inconsistent, and the markup would sometimes look alright, but most times, we would get the double <p>-tags.

To solve the problem we decided to simply add a field renderer, that would ensure that what comes from the Rich Text editor always get encapsulated with a <p>-tag. The implementation is a field renderer looking like this:

using System;
using Sitecore.Pipelines.RenderField;

namespace NAMESPACE
{
    public class EnsureTextTags
    {
        public void Process(RenderFieldArgs args)
        {
            if (args.FieldTypeKey != "rich text")
                return;
            if (args.Parameters.ContainsKey("ensureparagraph=1"))
            {
                string text = args.Result.FirstPart;
                if (!text.Trim().StartsWith("<p>"))
                {
                    text = String.Format("<p>{0}</p>", text);
                }
                args.Result.FirstPart = text;
            }
        }
    }
}

The above solution enables us to use the FieldRenderer with a parameter called ensureparagraph=1, which will check if the text starts with a <p>-tag, if it doesn’t, we add the <p>-tags. This ensures that what comes from the Rich Text Editor always gets encapsulated.

Using the FieldRenderer looks link this:

<sc:FieldRenderer runat="server" FieldName="Teaser text" Parameters="ensureparagraph=1" />

That’s it, simple, but saved some annoying html-weirdness on the frontend.

Patching is done via the Include folder via this config:

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <renderField>
        <processor
            patch:after="*[@type='Sitecore.Pipelines.RenderField.GetDocxFieldValue, Sitecore.Kernel']"
            type="NAMESPACE, ASSEMBLY"/>
      </renderField>
    </pipelines>
  </sitecore>
</configuration>