Cleaner Inline SVG using Templates

Inlining SVG code can get messy, and you don’t have to keep looking at it while you work on your Project.

December 5, 2016 - 2 minute read -

I’m a big fan of SVG for two good reasons, one being that the graphics always look good no matter the screen, and two, you can edit your graphics using CSS.

The only catch is, to make CSS edits to your SVG, you must inline the code, which is not pretty and can take up lots of room.

The way I keep my code from getting out of control is to use a templating language in my project. A templating language allows me to split pieces of code into their own file, and then include them with a simple tag.

The main concept here is to create a file that just houses your SVG code and then you can include the code with a template tag. This allows you to have the full SVG code in production, but when you are developing you only see what you need to see.

<!-- icon.nunjucks  -->
<svg width="100" height="100">
  <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />

<!-- icon_two.nunjucks  -->
<svg width="100" height="100">
    <rect x="10" y="10" height="100" width="100" style="stroke:#ff0000; fill: #0000ff"/>

<!-- index.twig -->
<div class="icons">
  {% include icon.nunjucks %}
  {% include icon_two.nunjucks %}

These examples show pretty simple SVG files but they get much more complicated.

I’ve used liquid templates in Shopify, and with the help of timber, Twig templates in Wordpress. Both of these tempting languages share a similar syntax which helps keep things easy.

For static sites, since I always use Node I found a gulp plugin that renders nunjucks, a language with a similar syntax to Twig & Liquid but based on javascript.

I won’t go into detail on how to set it up, but I do recommend following this post.