LoginSignup
6
3

More than 3 years have passed since last update.

Railsでsvg画像つこてみた

Last updated at Posted at 2020-12-05

はじめに

皆さんこんにちは、駆け出しエンジニアのプージニアです!
先週初投稿を果たし、本記事2本目でございます!

本記事はRailsでsvg画像を読み込んでつこてみた記事になります😁

対象の読者

・svgをRailsで使ってみたい!

参考

ヘルパーメソッド参考
https://coderwall.com/p/d1vplg/embedding-and-styling-inline-svg-documents-with-css-in-rails

Applicationヘルパーを作成する

application_helper.rb
# viewでsvg形式のファイルを読み込む
  def embedded_svg filename, options={}
    file = File.read(Rails.root.join('app', 'assets', 'images', filename))
    doc = Nokogiri::HTML::DocumentFragment.parse file
    svg = doc.at_css 'svg'
    if options[:class].present?
      svg['class'] = options[:class]
    end
    doc.to_html.html_safe
  end

コードの詳細は以下の参考サイトご覧ください!
僕の知見が増えてきたらコードの解説も編集して投稿する予定です

headerでつこてみる

以下サンプルコードはアプリケーションのロゴにsvg画像を採用する場面を想定しております

_header.html.erb
<%= link_to embedded_svg("application-logo.svg",
class: "application-logo",alt: "ApplicationName logo"), root_path %>

挿入したsvg画像のいじり方

分かりやすい記事なので是非下記参考にしてください
https://qiita.com/yamaking/items/3e2528ef7960c3b6ed9a

まとめ

皆さん無事にsvg画像表示されましたでしょうか?
表示されないよーって方はご質問頂ければわかる範囲でお答え致します👍

最後まで読んで頂きありがとうございます!

参考文献

https://qiita.com/yamaking/items/3e2528ef7960c3b6ed9a
https://coderwall.com/p/d1vplg/embedding-and-styling-inline-svg-documents-with-css-in-rails

6
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
3