Last active
May 16, 2020 08:12
-
-
Save tulios/f5091ede81c9f4b36785 to your computer and use it in GitHub Desktop.
embedded_svg helper for Rails
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 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 |
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 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 |
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
<%= embedded_svg "sample.svg", class: "svg-icons signal" %> | |
<%= embedded_svg "dir_inside_root/sample.svg", class: "svg-icons signal" %> |
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
@tulios second example does not work on rails (4.2.4) :(