Posted in: Comments

When inserting dynamic content into the editor it gets surrounded with a p-element if you're inserting it into a new paragraph.

Let's say our dynamic content Teasers renders a div-element as a wrapper, the page won't validate beacause it's not valid to have a div in a p.

We can easily fix this before the PageData gets persisted.

First we need to listen to some DataFactory events in global.asax.

protected void Application_Start(object sender, EventArgs e)
{
    EPiServer.DataFactory.Instance.CreatingPage 
        += new EPiServer.PageEventHandler(CreatingOrSavingPage);
    EPiServer.DataFactory.Instance.SavingPage 
        += new EPiServer.PageEventHandler(CreatingOrSavingPage);
}

Then we need to find all long strings in our PageData object that might have a dynamic content.

With some regular expression magic we strip surrounding p-elements if we find any, in this case we´re looking for a dynamic content called Teasers.

private void CreatingOrSavingPage(object sender, EPiServer.PageEventArgs e)
{
    if (e.Page != null)
    {
        foreach (var property in e.Page.Property)
        {
            if (property.Type == EPiServer.Core.PropertyDataType.LongString)
            {
                property.Value = Regex.Replace(
                    property.Value as string ?? string.Empty,
                    "<p>\\s*(?<DynamicContent><span[^>]*>{DynamicContent:Teasers}</span>)\\s*</p>",
                    "${DynamicContent}",
                    RegexOptions.Compiled | RegexOptions.IgnoreCase);
            }
        }
    }
}