4

Is it possible to remove empty html Tags like

<p>&nbsp;</p>

from RTE, because they are getting inserted very easy and destroying the design.

The best would be automaticaly :-) on save or publish.

3

You can use item:saving event. Be aware that in some cases saving of the item can be intercepted so not necessarily your changes will be saved.

<sitecore>
  <events>
    <event name="item:saving">
      <handler type="My.Assembly.Namespace.RemoveEmptyParagraphsFromRichTextProcessor,
        My.Assembly" method="OnItemSaving" />
    </event>
  </events>
</sitecore>

and the code

public class RemoveEmptyParagraphsFromRichTextProcessor
{
    protected void OnItemSaving(object sender, EventArgs args)
    {
        Item newItem = Event.ExtractParameter(args, 0) as Item;

        if (newItem == null || newItem.Database.Name != "master")
        {
            return;
        }

        Item originalItem = newItem.Database.GetItem(newItem.ID, newItem.Language, newItem.Version);

        var differences = FindDifferences(newItem, originalItem);

        foreach (var fieldName in differences)
        {
            var value = newItem[fieldName];
            if (!string.IsNullOrEmpty(value))
            {
                newItem[fieldName] = RemoveParagraphWithSpace(value);
            }
        }
    }

    private List<string> FindDifferences(Item newItem, Item originalItem)
    {
        newItem.Fields.ReadAll();

        return newItem
            .Fields
            .Where(x => x.Type.Equals("Rich Text"))
            .Select(f => f.Name)
            .Where(fieldName => newItem[fieldName] != originalItem[fieldName])
            .ToList();
    }

    private string RemoveParagraphWithSpace(string html)
    {
        // you can be more creative here
        return html.Replace("<p>&nbsp;</p>", "");
    }
}
| improve this answer | |
  • 1
    Only thing I would suggest is to consider using HtmlAgilityPack instead of a string replace. – Matthew FitzGerald-Chamberlain Aug 30 '19 at 18:02
  • 1
    @MatthewFitzGerald-Chamberlain that's why I used "you can be more creative here" comment. Question was only about removing p tag with space in it. If that's the only requirement then string.replace is much faster. If more complex processing of html is needed, HtmlAgilityPack is the good way. You're right. – Marek Musielak Sep 1 '19 at 13:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.