LoginSignup
0
0

More than 3 years have passed since last update.

【Rails】画像をasset pipelineを使わずに静的に表示する方法 & image_tagでid/クラス/altを指定する方法。

Last updated at Posted at 2021-04-13

Railsで画像をasset pipeline(image_tag)を使わずに静的に表示する方法について。

対処法

app > public配下に画像を保存し、src属性にpublic配下のパスを記述する。

<img src="public配下の画像パス" alt="">

▼例
public/assets/imgs/bear-icon-blue.svg を読み込む場合
image.png

<img src="assets/imgs/bear-icon-white.svg" alt="">



▼ブラウザの表示
image.png

画像の読み込みに成功。

注意点

assets配下の画像をsrc属性で指定して読み込むことはできない。NotFoundのエラーが出る。(昔のRailsでは読み込めたらしい)


asset pipelineで読み込む方法

Railsでより一般的なのはasset pipelineを使う方法。
この場合、asset > images配下と、public配下のどちらでも読み込むことができる。

・asset > images配下: パスの冒頭に/不要。
・public配下: パスの冒頭に/が必要。

1. asset > images配下の場合

<%= image_tag 'asset > images配下の画像パス' %>

▼実例

image.png

<%= image_tag 'bear-icon-white.svg' %>


2. public配下の場合

<%= image_tag '/public配下の画像パス' %>

▼実例

image.png

<%= image_tag '/assets/imgs/bear-icon-white.svg' %>


images_tagでid, class, altを指定する方法

属性名: "値"で記述する。

 <%= image_tag "画像パス", id: "id名", class: "クラス名", alt: "alt名", width: "幅" , height: "高さ" %>



▼実例

<%= image_tag 'bear-icon-white.svg', class: "icon-mage", alt: "白熊" %>

:の後ろにスペースがなくても機能する。

image.png



以上。

0
0
0

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
0
0