Hiding Empty Publishing Fields in a Page Layout

Most of the time when you’re rendering web content that content will exist in a container or have a header or a footer, etc. If you’re rendering an HTML publishing field within SharePoint the user could have simply left the field blank (unless you make the field required of course). In this case you probably don’t want to render the container/header/footer if there isn’t going to be any content. So let’s get down to business…

First you have you’re normal code

<h3>Publishing Header</h3>
<publishingwebcontrols:richhtmlfield id="PublishingContent1" fieldname="PublishingContent" runat="server"></publishingwebcontrols:richhtmlfield>

This is fine but we don’t want “Publishing Header” showing if there is no content in the field. So what do we do? First drop the following code at the beginning of the “PlaceHolderMain” in your custom page layout.

<script runat="server">
public static bool FieldHasValue(SPListItem item, string fieldName)
if (item.Fields.ContainsField(fieldName) && item[fieldName] != null)
string html = item[fieldName].ToString();
Regex regex = new Regex(@"\s]+))?)+\s*|\s*)/?>", RegexOptions.Singleline);
MatchCollection matches = regex.Matches(html);
foreach (Match match in matches)
html = html.Replace(match.Value, "");
html = html.Replace("\n", "").Trim();
return (html.Length > 0);
return false;

Now we just have to use some inline ASP to check the field before we do our rendering.

if (FieldHasValue(item, "PublishingContent"))
Response.Write("<h3>Publishing Header</h3>");
<publishingwebcontrols:richhtmlfield id="PublishingContent1" fieldname="PublishingContent" runat="server"></publishingwebcontrols:richhtmlfield>
I'm a public speaker and the Chief SharePoint Architect for Eastridge, a Microsoft Gold Partner specializing in SharePoint and custom application development in Winston-Salem, NC. I focus on the SharePoint platform with a specialty in Information Architecture, Publishing and Best Practices.

Got something to say? Go for it!