Bad Spaces

Written by @marcemarc on Monday, 29 February 2016

So the Tiny MCE Rich Text Editor has been adding a lot of extra <p></p> tags and <p>&nbsp;</p> in Umbraco recently; Bad spaces - particularly when inserting Macros it seems.

In the past I've played with the Tiny MCE config, and used the 'forced_root_block' setting and that has prevented them from being added: see an article here on how to do that:

http://scottsdevblog.com/2011/08/get-rid-of-those-pesky-p-tags-in-umbracos-tinymce-editor/

but somehow, on this last project I was working on - I couldn't get it to work like it used to :-( let me know if it still works right ? (probably just caching or something)

Anyway I didn't have time to mess around, tweaking and hoping and F5ving; and so instead, I hooked into the ContentService's saving event, checked for my rich text editor property (with alias 'content'), and used a Regex to strip out any empty paragraphs:

void ContentService_Saving(IContentService sender, Umbraco.Core.Events.SaveEventArgs e)
{
   foreach (var content in e.SavedEntities)
   {
      if (content.HasProperty("content"))
      {
         var contentHtml = content.GetValue("content");
         if (contentHtml != null)
 { // remove empty paragraphs var removeBlankParasRegex = @"<p[^>]*>(\s| |)*"; var strippedHtml = Regex.Replace(contentHtml.ToString(), removeBlankParasRegex, ""); // remove empty paragraphs with a non breaking space content.SetValue("content",strippedHtml);

} } } }

The nice thing about this approach is the editors get immediate feedback when they save, that the rogue spacing has been removed before they publish.

Whereas if you are relying on:

@Umbraco.Field("propertyAlias", removeParagraphTags:true)

then it will still look a bit messy in the back office.

To register the saving event, create a class that inherits ApplicationEventHandler, and override ApplicationStarting to hook up to the saving event:

public class ApplicationStartUp : ApplicationEventHandler
{
   protected override void ApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
   {
      ContentService.Saving += ContentService_Saving;
   }
}