AR삽질러

Rails 一日一つメソッド (Day27) image_tagメソッド 본문

Ruby/RubyOnRails-日本語

Rails 一日一つメソッド (Day27) image_tagメソッド

아랑팡팡 2024. 2. 2. 11:47
728x90

 

Rails 一日一つメソッド (Day27) image_tagメソッド

 

image_tagとは?

 - railsで画像を表紙するためのimgタグを作成するヘルパーメソッドで、image_tagを使うことによって、簡単にimgタグを作成できる。

 - image_tagヘルパーは、imageの名前、大きさ、class, id, alt textのようなHTMLオプションを引数で受けてHTML<img>タグを動的に生成する。

 

image_tagの使い方

 1) image_tag helper使用

  - file名 : image fileの名前を表す。

  - option : HTML属性をハッシュ形式で提供する。alt, class, is, styleなど。。

<%= image_tag "file名", "Option" %>

 

 2) HTML<img>タグ使用

  - src : image fileのURLを指定する。

<img src="/asserts/test.png" />

 

classの指定

 - image_tagのhelperで使う classオプションはHTMLの class属性を指定する時に使われる。

<%= image_tag 'test.png', class: 'testimg' %>
# css_file
.testimg {
	width: 100px;
    height: auto;
}

 

imageのサイズ

 - imageのサイズは sizeオプションで指定できる。

 - width, height

<%= image_tag "test_image1.png", size: "100x100" %>
<%= image_tag "test_image2.png", width: "100", height: "100" %>
<%= image_tag "test_image3.png", class: "testimg" %>
# css_file
.testimg {
	width: 100px;
    height: auto;
}

 

image_tagでのalt

  - 画像が表紙されない時に代替textを指定できる。

<%= image_tag "testimg.png", alt: "altの内容" %>

 


 

# view

<h1>Pages#home</h1>
<p>Find me in app/views/pages/home.html.erb</p>

<% flash.each do |key, value| %>
    <div class="flash <%= key %>"><%= value %></div>
<% end %><br>

<%= link_to '会員登録', signup_path %><br><br>

<%= link_to 'ユーザList', users_path %><br><br>

<%= link_to 'Login', login_path %><br>

<%= image_tag "testimg.png", size: '100x100' %>
<%= image_tag "testimg.png", width: '200', height: '200' %>
<%= image_tag "testimg.png", class: 'image_tag' %>

 

# css
.image_tag {
    width: 250px;
    height: 250px ;
}

 

https://github.com/designAR/rails_method_study/tree/day27_image_tag

 

GitHub - designAR/rails_method_study

Contribute to designAR/rails_method_study development by creating an account on GitHub.

github.com

 

728x90
반응형
LIST