Sitecore - Animated SVGs

 For versions prior to Sitecore 8.1 update 2 some gymnastics needed to be done in order to support SVGs (you can refer to https://cmsxperience.com/2016/03/31/render-svg-images-in-razor-with-sitecore/). For later versions, that support comes OOTB. However, there might be times where we need to display animated SVGs, and those animations don't always work when the SVGs get displayed inside a <img> tag. This post is a modification to the blog post linked above, we will update the code so that our SVGs can be animated and can be available on image search: 

 public static MvcHtmlString RenderSvg(this HtmlHelper helper, string imageSrc, string imageAlt, string className)  
     {  
       if (string.IsNullOrEmpty(imageSrc))  
       {  
         return new MvcHtmlString("<!-- No Image to display -->");  
       }  
       return !imageSrc.Contains(".svg")   
         ? new MvcHtmlString($"<img src='{imageSrc}' alt='{imageAlt}' class='{className}' />")  
         : new MvcHtmlString($"<object type='image/svg+xml' data='{imageSrc}' class='{className}'><img src='{imageSrc}' alt='{imageAlt}'/></object>");  
     }  

This code can be used in our views by doing something like this (I'm using Constellation's ModelMapper to get the src and alt for my SVG stored in Sitecore): 

 @Html.RenderSvg(Model.CategoryIconSrc, Model.CategoryIconAlt, "class_name")  

The output would be something like this:

 <object type="image/svg+xml" data="categoryicon.svg" class="class_name">  
 <img src="categoryicon.svg" />  
 </object>  

If we use <object> to render our SVG the image will not be available on image search and that's why we add the <img> as a fallback. 


Comments