Milkman Matty

SVGs are great; they're small, they scale and they are easily customisable. These qualities makes them the perfect fit for use in Umbraco 9.

Most of the properties of SVGs can be editied out of the box or through the normal CSS means. Those that can't can be changed easily by JavaScript, but what if JavaScript can't be used? Here's a pretty slick way to change the colour of an SVG in Umbraco v9 without using JavaScript.

Firstly, create a Media Picker and Color Picker on the back-office node of choice.

Next open your SVG in notepad. Ensure that a fill property is on each of the SVG's path tags. It doesn't matter what that value is set to because it will be overwritten, but the property must exist on the path (or equivalent) for this to work.

<svg viewBox="0 0 32 32" xmlns="">
    <path d="..." color="currentColor" fill="#000"></path>

Adding color="currentColor" is a fallback and is not strictly needed.

With that out of the way the real fun can begin. Upload the SVG to the picker and select a colour:

Next head over to the View(s) that you want to display the SVG on and add this bit of code:

  var helperIconUrl = Model.Value<IPublishedContent>("helperIcon") != null ?
    Model.Value<IPublishedContent>("helperIcon").Url() :

  var helperSvg = helperIconUrl != "" ?
    System.IO.File.ReadAllText(HostingEnvironment.WebRootPath + helperIconUrl) :
  //using basic replace
  var helperResult = helperIconUrl != "" ?
    helperSvg.Replace("#000", "#" + (Model.Value("helperIconColour"))) :
  //could also use regex
  //make sure to import lib: using System.Text.RegularExpressions
  var helperRegex = helperIconUrl != "" ?
    Regex.Replace(helperSvg, @"fill=\".*?\"", "fill='"+Model.Value("helperIconColour")+"'") :

//Output the modified SVG directly into the view.

The SVG is grabbed from the Media Picker that was set up earlier, and if the value isn't null then the Url of the SVG is saved. Next, the contents of the SVG is read into a variable by clever use of the System.IO.File class. From there its very easy to manipulate the SVG contents as a string. In this case the fill property is replaced with whatever colour was selected in the Color Picker.