Is it possible to remove empty html Tags like
<p> </p>
from RTE, because they are getting inserted very easy and destroying the design.
The best would be automaticaly :-) on save or publish.
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> </p>", "");
}
}
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.