Last active
October 5, 2016 16:02
-
-
Save bradjones1/1ef04432f096a49d77de to your computer and use it in GitHub Desktop.
Compass inline svg with string replacement (e.g., for fills)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage example