Skip to content

Instantly share code, notes, and snippets.

@tulios
Last active May 16, 2020 08:12
Show Gist options
  • 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
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="512px" height="512px" viewBox="0 0 512 512" enable-background="new 0 0 512 512" xml:space="preserve">
<path fill="#333333" d="M437.02,437.019l-45.25-45.25c74.984-74.983,74.984-196.557,0-271.54l45.25-45.25
C536.992,174.955,536.992,337.046,437.02,437.019z M369.137,369.136l-45.255-45.255c37.491-37.49,37.491-98.274,0-135.765
l45.255-45.255C431.62,205.346,431.62,306.653,369.137,369.136z M301.255,301.255c-24.993,24.993-65.517,24.993-90.51,0
c-24.994-24.992-24.994-65.516,0-90.51c24.993-24.994,65.517-24.994,90.51,0S326.248,276.261,301.255,301.255z M188.118,323.883
l-45.256,45.255c-62.483-62.483-62.483-163.79,0-226.274l45.256,45.255C150.628,225.608,150.628,286.391,188.118,323.883z
M120.23,391.769l-45.25,45.25c-99.974-99.975-99.974-262.064,0-362.039l45.25,45.25C45.246,195.214,45.246,316.786,120.23,391.769z
"/>
</svg>
<%= 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