LoginSignup
8
7

More than 5 years have passed since last update.

部分テンプレートrender partialを使用する際、collectionで変数を渡し、partial側でローカル変数で参照できる

Last updated at Posted at 2016-05-20

render partialオプション
renderメソッドに :partialというオプションをつけることで、明示的に部分テンプレート名を指定し、部分テンプレートを表示することができます。

コレクションをレンダリングする
パーシャルはデータの繰り返し (コレクション) を出力する場合にもきわめて便利です。:collectionオプションを使用してパーシャルにコレクションを渡すと、コレクションのメンバごとにパーシャルがレンダリングされて挿入されます。

index.html.erb
<h1>Products</h1>
<%= render partial: "product", collection: @products %>

_product.html.erb
<p>Product Name: <%= product.name %></p>

パーシャルを呼び出す時に指定するコレクションが複数形の場合、パーシャルの個別のインスタンスから、出力するコレクションの個別のメンバにアクセスが行われます。このとき、パーシャル名に基づいた名前を持つ変数が使用されます。上の場合、パーシャルの名前は_productであり、この_productパーシャル内でproductという名前の変数を使用して、出力されるインスタンスを取得できます。

参照:http://railsguides.jp/layouts_and_rendering.html

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