-
Advanced display of SVG Images in Sitecore
July 31, 2015 Rodrigo Peplau 0
SVG Images are basically vector images (coordinates, objects and properties) with data that can be manipulated with CSS styling – check out this article for details on how that works.
In short, to take advantage of CSS styling over SVG files, you must throw the XML content of the SVG file, directly into the HTML markup. So instead of the traditional <img tag:
<img src="image.svg"
You must throw inline the content of the SVG file, which will be something like:
<svg ...> <ellipse class="chair" .../> </svg>
In Sitecore that means you can’t use the standard sc:Image control to render the content of an Image Field – that will render your SVG as an <img HTML tag, which can’t be touched by CSS styling…
Usercontrol
In order to have something that is compatible both with CSS Styling and Sitecore’s Page Editor mode, my proposal is to have a custom asp usercontrol like this:
Image.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Image.ascx.cs" Inherits="Layouts.UserControls.Image" %> <sc:Image runat="server" ID="scImage" /> <asp:Literal runat="server" ID="litImage"></asp:Literal>
Image.ascx.cs (Codebehind)
namespace Layouts.UserControls { public partial class Image : UserControl { /// <summary> /// Component's Field /// </summary> public string Field { get; set; }
/// <summary> /// Component's Item (Default=Context) /// </summary> public Item Item { get { return _item ?? Sitecore.Context.Item; } set { _item = value; } } private Item _item;
protected void Page_Load(object sender, EventArgs e) { // When editing in Page Editor mode, always use an <sc:image // If no field is set, escape and let it break if (Sitecore.Context.PageMode.IsPageEditorEditing || string.IsNullOrEmpty(Field)) { ShowScImage(); return; }
// Escape if field is not found var referencedImageField = (Sitecore.Data.Fields.ImageField)Item.Fields[Field]; if (referencedImageField == null) { ShowScImage(); return; }
// Get referenced image - Scape if image is not found var imageItem = referencedImageField.MediaItem; if (imageItem == null) { ShowScImage(); return; }
// If this is not an svg use a normal <sc:Image var imageMediaItem = (MediaItem) imageItem; if (!imageMediaItem.Extension.ToLower().Contains("svg")) { ShowScImage(); return; }
ShowSvgImage(imageMediaItem); }
public static string GetMediaUrlWithServer(MediaItem mediaItem, Item item = null) { item = item ?? Sitecore.Context.Item; var options = new UrlOptions { AlwaysIncludeServerUrl = true, AddAspxExtension = false }; var itemUrl = LinkManager.GetItemUrl(item, options); var mediaOptions = new MediaUrlOptions { AbsolutePath = true }; var mediaUrl = MediaManager.GetMediaUrl(mediaItem, mediaOptions); return itemUrl + mediaUrl; }
private void ShowSvgImage(MediaItem mediaItem) { litImage.Visible = true; scImage.Visible = false;
// Get string from Image Stream var stream = mediaItem.GetMediaStream(); var reader = new StreamReader(stream); var svgString = reader.ReadToEnd(); reader.Close(); stream.Close();
// Get SVG tag from string
// No SVG tag found - fallback to <sc:Image if (!svgString.Contains("<svg")) { ShowScImage(); return; }
svgString = svgString.Substring(svgString.IndexOf("<svg",StringComparison.Ordinal)); litImage.Text = svgString; }
private void ShowScImage() { litImage.Visible = false; scImage.Visible = true;
scImage.Item = Item; scImage.Field = Field; ReflectAttributesToControl(scImage); }
private void ReflectAttributesToControl(WebControl control) { foreach (string key in Attributes.Keys) control.Attributes[key] = Attributes[key]; } }
Streaming
The proposed solution makes use of Streaming for better performance, so rendering times are not affected.
How to Use
Now we have our custom image rendering control that renders inline SVG images when you are in Preview or Normal mode, and is compatible with Sitecore’s Page Editor mode.
To use, first you have to register the Usercontrol:
<%@ Register TagPrefix="custom" TagName="Image" Src="~/layouts/UserControls/Image.ascx" %>
Then use it just like you’d do with a standard sc:Image control:
<custom:Image runat="server" ID="imgSvgImage" Field="My Field Name" />
At the code behind you can also access the properties “Field” and “Item” just like the normal Image control:
imgClear.Item = Sitecore.Context.Item;
And that’s all!
Categories: Architecture, Experience Editor, Front-end, Uncategorized
Using Rules to replace spaces by dashes in Sitecore 7.5 in 3 simple steps Avoiding IIS Restarts in a separated code environment, now with Sitecore Rocks
Proudly 9x Sitecore MVP
(2016-2024)
Localization
Recent Posts
Recent Comments
- navan on Meet MVPinny: the AI-Powered Sitecore Assistant
- Adriana on Content generation with Sitecore Connect and ChatGPT
- NAVAN on Automatic Sitecore NuGet upgrades with Powershell
- Hedipo S Menezes on Corey Peplau wrote this - WFFM conflict with Unity DI and a lesson on how Sitecore community is so amazing
- Rodrigo Peplau on ERROR [Content Testing]: Cannot find PhantomJS executable at ' (...) /data/tools/phantomjs/phantomjs.exe'. Aborting screenshot generation.
Archives
- June 2024
- April 2024
- February 2024
- December 2023
- November 2023
- August 2023
- July 2023
- January 2023
- February 2022
- December 2021
- November 2021
- March 2021
- July 2020
- February 2020
- September 2019
- July 2019
- April 2019
- March 2019
- December 2018
- February 2018
- January 2018
- November 2017
- September 2017
- August 2017
- July 2017
- March 2017
- February 2017
- November 2016
- September 2016
- August 2016
- July 2016
- April 2016
- November 2015
- September 2015
- July 2015
- April 2015
- March 2015
- February 2015
Categories
- Actions
- Active Directory
- Analytics
- Architecture
- Bug fixing
- CDP/Personalize
- ChatGPT
- Content Edition Experience
- Content Hub
- Continuous Integration
- Dev
- Development
- Environments
- Experience Editor
- Experience Forms
- Front-end
- Health Check builds
- Helix
- How To
- LDAP
- MVP
- MVP Summit
- MVPinny
- Phantom JS
- Powershell
- QA
- Richtext Editor
- Rules
- Security Provider
- SIF
- Sitecore 9
- Sitecore API
- Sitecore Community
- SItecore Connect
- Sitecore Modules
- Sitecore Rocks
- Sitecore Rule Processor
- Sitecore Symposium
- SPE
- SPEAK
- SUG
- Support Ticket
- TDS
- Team City
- Uncategorized
- Upgrades
- Visual Studio
- WFFM
- Workflow
- XConnect
- xDB
- XM Cloud