Skip to content

Instantly share code, notes, and snippets.

@tulios
Last active May 16, 2020 08:12
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tulios/f5091ede81c9f4b36785 to your computer and use it in GitHub Desktop.
Save tulios/f5091ede81c9f4b36785 to your computer and use it in GitHub Desktop.
embedded_svg helper for Rails
module ApplicationHelper
# Using raw files
def embedded_svg filename, options = {}
root = options[:root] || Rails.root.join("app", "assets", "svgs")
file = File.read(File.join(root, filename))
doc = Nokogiri::HTML::DocumentFragment.parse file
svg = doc.at_css 'svg'
svg['class'] = options[:class] if options[:class].present?
doc.to_html.html_safe
end
end
module ApplicationHelper
# Using Sprockets (AssetPipeline) to fetch the files
def embedded_svg_v2 filename, options = {}
content = Rails.application.assets.find_asset(filename).body.force_encoding("UTF-8")
doc = Nokogiri::HTML::DocumentFragment.parse content
svg = doc.at_css 'svg'
svg['class'] = options[:class] if options[:class].present?
doc.to_html.html_safe
end
end
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
<%= embedded_svg "sample.svg", class: "svg-icons signal" %>
<%= embedded_svg "dir_inside_root/sample.svg", class: "svg-icons signal" %>
@davetoxa
Copy link

@tulios second example does not work on rails (4.2.4) :(

@choilive
Copy link

choilive commented May 16, 2020

for svg v2 i needed to change
content = Rails.application.assets.find_asset(filename).body.force_encoding("UTF-8")
to
content = Rails.application.assets.find_asset(filename).source.force_encoding("UTF-8")

Although it works fine, unfortunately it is pretty slow. I am seeing that rendering takes an additional 1ms PER svg.
If SVGs are used extensively in your application, I would look for another solution.

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