LoginSignup
1
0

More than 5 years have passed since last update.

Railsの部分テンプレ(partial)をラッピングして、collection変数を渡す

Posted at

TL;DR

_item.html.slim
h3 Item Name: #{item.name}
p Item Index: #{item_counter}
_wrapped_item.html.slim
h2 Item Wrapper
.item-area
  = render partial: 'item',\
    locals: { item: wrapped_item, item_counter: wrapped_item_counter }
index.html.slim
h1 Naked Items
.naked-items = render partial: 'item', collection: @items

h1 Wrapped Items
.wrapped-items = render partial: 'wrapped_item', collection: @items

はじめに

パーシャルをrenderする際、<%= render partial: 'item', collection: @items %>を使うと、.each文より見通しが良くなるだけでなく、性能も向上されるとされています。
しかし、パーシャルにそれぞれラッピングやデコレーションをしたい場合、どうすれば良いのでしょう。

発見

_item.html.slim
h3 Item Name: #{item.name}
p Item Index: #{item_counter}
_wrapped_item.html.slim
h2 Item Wrapper
.item-area = render partial: 'item'
index.html.slim
h1 Naked Items
.naked-items = render partial: 'item', collection: @items

h1 Wrapped Items
.wrapped-items = render partial: 'wrapped_item', collection: @items

上記の構文のように、そのまま_item.html.slimにラッピングを当てて、renderingしようとする時、Template::Errorが発生し、変数itemがないと言われました。

ActionView::Template::Error (undefined local variable or method `item' for #<#<Class:0x00007f8d8fa105d0>:0x00007f8da6f657a8>:
    1: h3 Item Name: #{item.name}
    2: p Item Index: #{item_counter}

だったら変数itemを手動で渡せば良いのでは?と思って、変数wrapped_itemitemとして渡しました。もちろん、Indexも必要な時は、#{variable_name}_countも伝播しなければいけません。

_wrapped_item.html.slim
h2 Item Wrapper
.item-area
  = render partial: 'item',\
    locals: { item: wrapped_item, item_counter: wrapped_item_counter }

参考

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