Using EnclosingTag in Page Editor

Posted 10/28/2013 by vconcepcion

A nice feature of the FieldRenderer control that I don't see used often enough is the EnclosingTag property. Often you'll have some text field that needs to be wrapped in an HTML tag, for example:

My Subtitle

I typically see people implement this with something like the following...

<sc:FieldRenderer ID="frSubtitle" runat="server" FieldName="Subtitle" />

...which is fine if the field is required or guaranteed to have a value, but not-so-fine when the field is optional, resulting in an empty <h2> and likely some unnecessary line spacing.

To address this, rather than making the <h2> a server control whose Visible property is set based on the presence of a field value (and the Sitecore.Context.PageMode), you can simply do the following:

<sc:FieldRenderer ID="frSubtitle" runat="server" FieldName="Subtitle" EnclosingTag="h2" />

If the field value is empty, the enclosing tag will not be rendered.

But wait!

One gotcha in Page Editor: editing and saving a "Single-Line Text" field that uses this will result in the EnclosingTag being included in the saved field value. For example, when you save a change, the field value will be updated to "<h2>My Subtitle</h2>" instead of just "My Subtitle".

This has been registered as a bug for the current version of Sitecore (7.0 rev. 130918), but here's the workaround Sitecore Support gave me:

        <processor type ="Sitecore.Pipelines.RenderField.RenderWebEditing, Sitecore.Kernel" />
        <processor type ="Sitecore.Pipelines.RenderField.AddBeforeAndAfterValues, Sitecore.Kernel" />

They also gave me a disclaimer that this workaround is "not properly tested", but so far it's worked without issue for me.