DEV Community


Posted on

Using inline SVGs with Rails

Last night I spent about three hours fighting and struggling on how to get insert icons from zondicons and add some classes to them. Needless to say just adding an image_pack_tag was not doing the trick, as I needed something like this

<svg class="my-classes with-style">
  <path ...>

...instead of this

<img src="path/to/icon.svg" class="my-classes" />

So I made a helper for this:

module ApplicationHelper
  def zondicon(icon_name, options={})
    file ='app', 'javascript', 'images', 'zondicons', "#{icon_name}.svg"))
    doc = Nokogiri::HTML::DocumentFragment.parse file
    svg = doc.at_css 'svg'

    options.each {|attr, value| svg[attr.to_s] = value}


And now in my views I can do this:

<button class="btn btn-blue">
  <%= zondicon('wrench', class: 'fill-current teal-500') %>

There's also a gem called inline_svg for this very purpose, but I decided to go for a simpler approach with no extra dependencies.

Top comments (1)

thisdotmedia_staff profile image
This Dot Media

Glad you were able to solve the problem. Thanks for sharing this with your fellow devs 😇