Created
July 12, 2013 04:24
-
-
Save mipearson/5981422 to your computer and use it in GitHub Desktop.
Helper & Rake task for SVG fallback usage & generation. Assumes Rails w/asset pipeline, your svgs are all in app/assets/images/vector, and imagemagick & optipng are installed.
This file contains hidden or 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 AssetsHelper | |
| # SVG with PNG fallback for IE8. | |
| # Run rake app:svg_fallback to generate fallbacks | |
| def svg_image_tag source, *args | |
| options = args.extract_options! | |
| svg_class = options.fetch(:class, '') | |
| svg_class += ' svg' | |
| content = image_tag "vector/" + source, *args, options.merge(class: svg_class) | |
| content << "\n<!--[if lt IE 9]>\n".html_safe | |
| content << image_tag("vector/fallback/" + source.gsub('.svg', '.png'), *args, options) | |
| content << "\n<![endif]-->\n".html_safe | |
| content | |
| end | |
| end |
This file contains hidden or 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
| namespace :app do | |
| task :svg_fallback do | |
| desc "Create fallback images for SVGs in app/assets/vector" | |
| vector_dir = Rails.root.join(*%w{app assets images vector}) | |
| fallback_dir = vector_dir.join('fallback') | |
| Dir[vector_dir.join('**/*.svg')].each do |path| | |
| path = Pathname.new(path) | |
| file = path.relative_path_from(vector_dir) | |
| destination = fallback_dir.join(file) | |
| FileUtils.mkdir_p destination.dirname | |
| destination = destination.to_s.gsub(".svg", ".png") | |
| puts "Converting #{file}" | |
| system "convert -background none #{path} #{destination}" | |
| puts "Optimising .png with optipng" | |
| system "optipng --quiet #{destination}" | |
| end | |
| end | |
| end |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
.. also worth mentioning that we have CSS that hides .svg in IE8