Created
May 13, 2015 21:31
-
-
Save Jeavon/3ab8997354bf772e025e to your computer and use it in GitHub Desktop.
Umbraco RteCustomValueConverter to output data-rel attributes on images
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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