_k

Liquid svg-icon tag

To use svg icons on the site the following technique is used to include the icons in the html. Essentially it’s one svg file which holds all icons in their own symbol element which then can be referenced by it’s id.

<svg id="icons" xmlns="http://www.w3.org/2000/svg">
  <symbol id="twitter" viewBox="0 0 32 32">
    <title>Twitter</title>
    <path d="..."/>
  </symbol>
  ...
</svg>

To include the icon, a svg tag with an use statement is used.

<svg class="icon" role="img" width="24" height="24">
  <use xlink:href="/assets/icons.svg#twitter"></use>
</svg>

I recommend reading this article if you want to go in depth with this method.

While being accessible and performant it isn’t very comfortable to write. So i decided to build a liquid tag to let jekyll do the work.

module Jekyll
  class SvgiconTag < Liquid::Tag

    def initialize(tag_name, icon, tokens)
      super
      @icon = icon.gsub(/\s+/, "")
    end

    def render(context)
      "<svg class=\"icon\" role=\"img\" width=\"24\" height=\"24\">
        <use xlink:href=\"/assets/icons.svg\##{@icon}\"></use>
      </svg>"
    end
  end
end

Liquid::Template.register_tag('svgicon', Jekyll::SvgiconTag)

By invoking the following, the icon with the matching id is placed in the html.

{% svgicon twitter %}

Feel free to copy the liquid tag and use it on your site (gist here). To install it just drop it in the _plugin directory in your jekyll project and name the file however you want.