Skip to content

Instantly share code, notes, and snippets.

@bewards
Created July 23, 2020 14:37
Show Gist options
  • Save bewards/66159aad4ce0244719afbc474c153653 to your computer and use it in GitHub Desktop.
Save bewards/66159aad4ce0244719afbc474c153653 to your computer and use it in GitHub Desktop.
Sitecore RenderSVG HtmlHelper for svg-inject
using Sitecore;
using Sitecore.Data.Fields;
using Sitecore.Data.Items;
using Sitecore.Resources.Media;
using System;
using System.IO;
using System.Web.Mvc;
namespace Foundation.SitecoreHelpers.Extensions
{
public static class HtmlHelpers
{
public static MvcHtmlString RenderSvg2(this HtmlHelper htmlHelper, ImageField image)
{
if (image == null || image.MediaItem == null) { return new MvcHtmlString($"<!-- Empty {(image == null ? "Image Field" : "Media Item")} -->"); }
var imageMediaItem = new MediaItem(image.MediaItem);
if (Sitecore.Context.Item.Editing.IsEditing || imageMediaItem.MimeType != "image/svg+xml") {
return new MvcHtmlString(String.Format("<img src=\"{0}\" alt=\"{1}\" />", StringUtil.EnsurePrefix('/', MediaManager.GetMediaUrl(imageMediaItem)), image.Alt));
}
return new MvcHtmlString(string.Format("<img src=\"{0}\" alt=\"{1}\" onload=\"SVGInject(this)\" />", StringUtil.EnsurePrefix('/', MediaManager.GetMediaUrl(imageMediaItem)), image.Alt));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment