Skip to content

Instantly share code, notes, and snippets.

@bradjones1
Last active October 5, 2016 16:02
Show Gist options
  • Save bradjones1/1ef04432f096a49d77de to your computer and use it in GitHub Desktop.
Save bradjones1/1ef04432f096a49d77de to your computer and use it in GitHub Desktop.
Compass inline svg with string replacement (e.g., for fills)
module Sass::Script::Functions
def inline_svg_image(path, repl = nil)
real_path = File.join(Compass.configuration.images_path, path.value)
svg = data(real_path)
if repl && repl.respond_to?('to_h')
repl = repl.to_h
svg = svg.to_s
repl.each_pair do |k, v|
if svg.include? k.value
svg.gsub!(k.value, v.value)
end
end
end
encoded_svg = CGI::escape(svg).gsub('+', '%20')
data_url = "url('data:image/svg+xml;charset=utf-8," + encoded_svg + "')"
Sass::Script::String.new(data_url)
end
private
def data(real_path)
if File.readable?(real_path)
File.open(real_path, "rb") {|io| io.read}
else
raise Compass::Error, "File not found or cannot be read: #{real_path}"
end
end
end
@bradjones1
Copy link
Author

Usage example

// Icon mixin. Assumes square icon.
@mixin icon($name, $factor: 1, $fill: 'black', $library: 'icomoon', $grid: 16px) {
  display: block;
  height: $factor * $grid;
  width: $factor * $grid;
  content: '';
  background-image: inline-svg-image('icomoon/SVG/' + $name + '.svg', ( '#000000': inspect($fill)));
  background-size: cover;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment