2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

学習68日目

Posted at

内容

部分テンプレートの呼び出し方

前提

  • ruby on railsでアプリ開発中
  • 該当部分以外は省略

render partial

(例)
app/views/hoges/new.html.erb

<%= render partial: 'form', locals: {hoge: @hoge} %>

この場合、インスタンス変数の中身が複数となる場合、下記のように書く必要が出てくる。

<% @hoges.each do |hoge| %>
  <%= render partial: 'form', locals: {hoge: hoge} %>
<% end %>

render partial (collectionオプションつき)

(例)
app/views/hoges/new.html.erb

<% @hoges.each do |hoge| %>
  <%= render partial: 'form', locals: {hoge: hoge} %>
<% end %>

これは、collectionオプションをつけると下記のように書ける。

<%= render partial: 'form', collection: @hoges %>

render (省略系)

インスタンス変数名 と テンプレート名 が同じ場合のみ、partial等を省略できる。

(例)

  <%= render partial: 'tweet', locals: {tweet: @tweet} %>

これは、下記のように省略可能。

<%= render @tweet %>

(例)

<%= render partial: 'tweet', collection: @tweets %>

これは、下記のように省略可能。

<%= render @tweets %>

コメント

省略には厳密な条件があるので、慣れないうちは省略せずに書く。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?