Skip to content

Instantly share code, notes, and snippets.

@Jeavon
Created May 13, 2015 21:31
Show Gist options
  • Save Jeavon/3ab8997354bf772e025e to your computer and use it in GitHub Desktop.
Save Jeavon/3ab8997354bf772e025e to your computer and use it in GitHub Desktop.
Umbraco RteCustomValueConverter to output data-rel attributes on images
namespace MyProject.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");
img.Attributes.Add("data-rel", rel);
modified = true;
}
}
}
if (modified)
{
return doc.DocumentNode.OuterHtml;
}
}
}
return coreConversion;
}
}
}
namespace MyProject.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)
{
PropertyValueConvertersResolver.Current.RemoveType<RteMacroRenderingValueConverter>();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment