Skip to content

Instantly share code, notes, and snippets.

@kynatro
Last active November 23, 2016 22:42
Show Gist options
  • Save kynatro/807c0ccd6cf94a0eeba5993e120aae0a to your computer and use it in GitHub Desktop.
Save kynatro/807c0ccd6cf94a0eeba5993e120aae0a to your computer and use it in GitHub Desktop.
Middleman Embedded SVG Ruby Helper

Embedded SVG Helper

A simple helper function that makes inline SVG embedding simple! Just add the asset_helpers.rb file to your Middleman project's helpers folder and it will automatically be loaded and made available to you in your templates. From there, simply call:

<%= embedded_svg("my-asset.svg") %>

And your SVG asset content will be embedded inline in your template. You can also pass the following options to the helper to add additional attributes to the SVG tag itself:

Option Type Value
width String/Integer The width of the SVG with units (px or %) specified as a String. Also takes an Integer which assumes a unit of px
height String/Integer The height of the SVG with units (px or %) specified as a String. Also takes an Integer which assumes a unit of px
id String The id attribute of the SVG tag
class String The class attribute of the SVG tag
preserveAspectRatio String The preserveAspectRatio attribute of the SVG tag. See https://css-tricks.com/scale-svg/ for how you can wield this attribute to your advantage by assigning it dynamically.

Dependencies

This helper method relies on the Nokogiri gem for processing the SVG XML in order to add attributes to the tag. Ensure that Nokogiri is available in your project via Bundler by adding the following line to your Gemfile:

gem "nokogiri"

Or if for some reason you aren't using Bundler to manage your gems make sure its installed:

$> gem install nokogiri
module AssetHelpers
# Embed an SVG's contents inline
def embedded_svg(filename, options={})
real_path = filename.dup
real_path = File.join(config[:source], config[:images_dir], real_path) unless real_path.start_with?('/')
# Return nothing if the file doesn't actually exist
return "" if !File.file?(real_path)
file = File.open(real_path)
# Allow specification of a number only to imply px units
[:width, :height].each do |dimension|
options[dimension] = "#{options[dimension]}px" if /^(?<num>\d+)$/ =~ "#{options[dimension]}"
end
begin
doc = Nokogiri::HTML::DocumentFragment.parse file.read
svg = doc.at_css "svg"
[:class, :width, :height, :id, :preserveAspectRatio].each do |option|
svg["#{option}"] = options[option] if options[option].present?
end
svg
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment