Skip to content

Instantly share code, notes, and snippets.

@Jeavon
Created September 30, 2014 09:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Jeavon/d0626584762db978f4e8 to your computer and use it in GitHub Desktop.
Save Jeavon/d0626584762db978f4e8 to your computer and use it in GitHub Desktop.
Remove invalid rel tags from RTE images on render
namespace Crumpled.Logic.ValueConverters
{
using System.Linq;
using System.Web;
using HtmlAgilityPack;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Core.PropertyEditors;
using Umbraco.Core.PropertyEditors.ValueConverters;
using Umbraco.Web.PropertyEditors.ValueConverters;
[PropertyValueType(typeof(IHtmlString))]
[PropertyValueCache(PropertyCacheValue.All, PropertyCacheLevel.Request)]
public class RteCustomValueConverter : TinyMceValueConverter
{
public override object ConvertDataToSource(PublishedPropertyType propertyType, object source, bool preview)
{
if (source == null)
{
return null;
}
var coreConversion = new RteMacroRenderingValueConverter().ConvertDataToSource(
propertyType,
source,
preview);
var doc = new HtmlDocument();
doc.LoadHtml(coreConversion.ToString());
if (!doc.ParseErrors.Any() && doc.DocumentNode != null)
{
// Find all images with rel attribute
var imgNodes = doc.DocumentNode.SelectNodes("//img[@rel]");
if (imgNodes != null)
{
var modified = false;
foreach (var img in imgNodes)
{
var firstOrDefault = img.Attributes.FirstOrDefault(x => x.Name == "rel");
if (firstOrDefault != null)
{
var rel = firstOrDefault.Value;
// Check that the rel attribute is a integer before removing
int nodeId;
if (int.TryParse(rel, out nodeId))
{
img.Attributes.Remove("rel");
modified = true;
}
}
}
if (modified)
{
return doc.DocumentNode.OuterHtml;
}
}
}
return coreConversion;
}
}
}
namespace Crumpled.Logic.Events
{
using Umbraco.Core;
using Umbraco.Core.PropertyEditors;
using Umbraco.Web.PropertyEditors.ValueConverters;
public class UmbracoEvents : ApplicationEventHandler
{
protected override void ApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
// Remove the core Rte Value Converter as we have our own to remove the rel attributes
PropertyValueConvertersResolver.Current.RemoveType<RteMacroRenderingValueConverter>();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment