Skip to content

Instantly share code, notes, and snippets.

@frank-who
Created April 14, 2016 10:50
Show Gist options
  • Save frank-who/0d81fcd62d152c170c8db10d206ef824 to your computer and use it in GitHub Desktop.
Save frank-who/0d81fcd62d152c170c8db10d206ef824 to your computer and use it in GitHub Desktop.
SVG Sprite Helper

Assumptions:

  • Sketch was used to create the icons
  • Each icon was saved in it's own artboard

Include the code below in application.html.slim, just after the opening body

= svg_sprites(Rails.root.join('app/assets/images/sprites/*.svg'), 'sprites')

Then use the following to display the icon

= svg_icon('name-of-artboard-in-sketch')
module SvgSpriteHelper
def svg_icon(icon, options={})
options[:class] ||= []
options[:class] = ['icon', icon] + options[:class].split(' ')
content_tag(:svg, options) do
content_tag(:use, nil, 'xlink:href'=>"##{icon}")
end
end
def svg_sprites(sprites, prefix=nil)
content_tag(:svg, style:'display:none') do
Dir.glob(sprites).each do |svg_file|
concat svg_to_symbol(svg_file, prefix)
end
end
end
def svg_to_symbol(svg_file, prefix=nil)
svg_doc = Nokogiri::HTML(open(svg_file)) { |config| config.noblanks }
# Fetch attributes
svg = svg_doc.at_css('svg')
icon_name = svg_file.gsub('.svg', '').split('/').last
icon_id = [prefix, icon_name].compact.join('/')
# Get icon
icon_data = svg.at_css("[id^='#{icon_id}']")
icon_data.xpath('//@id').remove
ncount = 0
icon_data.traverse do |node|
ncount += 1
node[:class] = [icon_name, ncount].join('__')
end
# raise nodes.map{|n| n.name}.inspect
content_tag(:symbol, icon_data.to_html.html_safe, { id: icon_name, viewBox: svg['viewbox'] })
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment