LoginSignup
0
0

More than 5 years have passed since last update.

基礎Ruby on Rails Chapter3 テンプレート

Last updated at Posted at 2018-09-17

基礎Ruby on Rails Chapter3 コントローラ
基礎Ruby on Rails Chapter3 レイアウトテンプレート

テンプレート

テンプレートの書式

  • <%= %> に出力したい変数を入れる。
  • 変数は、to_sメソッドが呼ばれる。
  • 変数の値がnilの場合、変数の部分は何も表示されない。
  • コントローラのメソッドは、処理が必要なければ無くてもよい。
app/controllers/lesson_controller.rbの一部
  def step7
    # floorで小数点切り捨て
    @price = (2000 * 1.08).floor
  end
app/views/lesson/step7.html.erb
<p><%= @price %></p>

http://localhost:3000/lesson/step7 を開く。
image.png

renderメソッド

renderに、「アクション名」を指定すると、そのテンプレートが使用できる。

app/controllers/lesson_controller.rbの一部
  def step8
    @price = 1000
    render "step7"  # step8ではなく、step7.html.erbでレンダリングする
  end

http://localhost:3000/lesson/step8 を開く。
image.png

HTML特殊文字の変換

  • <>やシングルクォートなどの危険な文字は変換される。
app/controllers/lesson_controller.rbの一部
  def step9
    @comment = "<script>alert('危険!')</script>こんにちは。"
  end
app/views/lesson/step9.html.erb
<p><%= @comment %></p>

http://localhost:3000/lesson/step9 を開く。
image.png

ソース
image.png

  • <%== %>を使うと、そのまま出力される。
app/controllers/lesson_controller.rbの一部
  def step10
    @comment = "<strong>安全なHTML</strong>"
  end
app/views/lesson/step10.html.erb
<p><%== @comment %></p>

http://localhost:3000/lesson/step10 を開く。
image.png

書式の指定とヘルパーメソッド

数値、日付、文字列

  • step11 数値
lesson_controller.rb
  def step11
    @population = 704414
    @surface = 141.51
  end
  • %d 整数
  • %f 浮動小数点数(%3.2f=幅3、精度2。幅に満たない場合、半角空白が埋められる。精度は四捨五入。)
  • %s 文字列
app/views/lesson/step11.html.erb
<p><%= sprintf("人口%d人、面積平方%.0fキロ、人口密度%.2f人/平方キロ",
    @population, @surface, @population/@surface) %></p>

http://localhost:3000/lesson/step11 を開く。
image.png

  • step12 日付
lesson_controller.rb
  def step12
    @time = Time.current
  end
app/views/lesson/step12.html.erb
<p><%= @time.strftime("%Y/%m/%d(%a) %H:%M:%S") %></p>

http://localhost:3000/lesson/step12 を開く。
image.png

  • step13 3桁区切りの表示
lesson_controller.rb
  def step13
    @population = 127767944
  end
  • rubyだけではなく、RailsのAction Viewが備えているメソッドも利用できる。
  • 3桁ごとにカンマ区切りを表示させるには、number_with_delimiterメソッドを使う。
app/views/lesson/step13.html.erb
<p>人口<%= number_with_delimiter(@population) %></p>

http://localhost:3000/lesson/step13 を開く。
image.png

ヘルパーメソッドの作成

  • step14 ヘルパーメソッド
    • ヘルパーメソッドは、"コントローラ名_hepler.rb"にモジュールとして記述するが、そのコントローラだけではなく、どこからでも使える。名前の重複に注意する。

lesson_heper.rbを新規作成する。

  • hメソッドはHTML特殊文字を変換する(<>'等)
  • gsubは正規表現の置換を行う
  • html_safeは"<br />"をそのまま出力する
app/helpers/lesson_helper.rb
module LessonHelper
  def tiny_format(text)
    h(text).gsub("\n","<br />").html_safe
  end
end
lesson_controller.rb
  def step14
    @message = "ごきげんいかが?\nRailsの勉強がんばりましょう。"
  end  
app/views/lesson/step14.html.erb
<p><%= tiny_format(@message) %></p>

http://localhost:3000/lesson/step14 を開く。
image.png

リンクと画像

リンク

  • step15 リンク
    • link_to リンク(aタグ)を作成する。第1引数はリンクのテキスト、第2引数はパス。
    • root_pathは、「/」を返すメソッド。:rootと指定することもできる。
app/views/lesson/step15.html.erb
<p><%= link_to "Home", root_path %></p>

http://localhost:3000/lesson/step15 を開く。
image.png

  • link_toメソッドの第3引数には、ハッシュでmethodオプションやdataオプションを追加できる。
    • methodオプションはHTTPメソッドの種類を指定できる。
    • dataオプションはリンク先に進むかどうかを示す確認メッセージを表示する。
<%= link_to "削除", member, method: :delete, data: {confirm: "本当に削除しますか?"} %>
  • 「属性名:値」を指定すれば、aタグの属性になる。以下は、<a href="/" class="menu">の例。
<%= link_to "Home", root_path, class: "menu" %>
  • link_to_unless_currentは、現在のページだったらリンクにせず、テキストだけ表示する。
<%= link_to_unless_current "Home", root_path, class: "menu" %>

画像

  • step16 画像
    • 画像をapp/assets/imagesディレクトリに入れておく。
    • 第1引数には画像ファイル名、第2引数にはハッシュでオプションを指定する。オプションはHTMLのimgタグと同じものが指定できる。
app/views/lesson/step16.html.erb
<p><%= image_tag("rails-logo.svg", size: "64x20", alt: "Ruby on Rails", align: "top") %></p>

http://localhost:3000/lesson/step16 を開く。
image.png

一般的なタグの出力

  • Rubyのコードを使ってHTMLのタグを記述する必要があるときは、tagメソッドやcontent_tagメソッドを使う。
  • <br /><p class="p1">こんにちは</p>を出力する例
<%= tag(:br) %>
<%= content_tag(:p, class:"p1") do %>
こんにちは
<% end %>

image.png

条件分岐と繰り返し

条件分岐

  • step17
lesson_controller.rb
  def step17
    @zaiko = 10
  end
  • ifやunlessを入れることができる。
  • <%--%>で閉じると、その前/後の改行や空白は取り除かれる。
app/views/lesson/step17.html.erb
<% if @zaiko > 0 %>
残り<%= @zaiko -%>
個です。
<% else %>
品切れです。
<% end %>

http://localhost:3000/lesson/step17 を開く。
image.png
image.png

繰り返し

  • step18
lesson_controller.rb
  def step18
    @items = {"フライパン" => 2680, "ワイングラス" => 2550, 
      "ペッパーミル" => 4515, "ピーラー" => 945}
  end
app/views/lesson/step18.html.erb
<table border="1" cellpadding="4">
<% @items.each do |key,val| %>
  <tr>
  <td><%= key %></td>
  <td style="text-align:right"><%= number_with_delimiter(val) %></td>
  </tr>
<% end %>

http://localhost:3000/lesson/step18 を開く。
image.png

参考
改訂4版 基礎 Ruby on Rails (IMPRESS KISO SERIES)

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