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?

More than 5 years have passed since last update.

部分テンプレートを繰り返し表示させる方法

Posted at

1,はじめに

railsでビューを繰り返し表示させたい時、eachメソッドを使うことが多いと思います。

- @product.each do |product|
  %h3.item-title 
    = product.name

@productに入ってる配列の要素数分だけビューが出力されるようになります。

2,部分テンプレートを使用し繰り返し表示させるには?

eachメソッドを使わず部分テンプレートで繰り返し表示させる方法もあります。

部分テンプレートを繰り返し表示させるには、collectionオプションを使用します。

listing.html.haml

%ul
  %li
    = render partial: "list_content", collection: @products
_list_content.html.haml
%li
  = link_to "/products/#{product.id}/detail" do
    = image_tag  "#{product.images[0].image[:medium].url}" ,size: "48x48"
    .display--item
      %p 
        = product.name
      .display--item__status
        = icon "far fa-heart",class: "far fa-heart"
        %span 0
        = icon "far fa-comment-alt",class:"far fa-comment-alt"
        %span 0
        .display--item__status__awiting
          出品中

これでlist_content@productsの配列の要素数分だけ呼び出せることができます。

これで表示できるはずが...

エラーが発生してしまいます。原因は変数名の違いにありました。

listing.html.hamlでは@productsと変数名を定義しています。

しかし、_list_content.html.hamlでは変数名がproductになっているので、変数名をあわせてあげましょう。

listing.html.haml

%ul
  %li
    = render partial: "list_content", collection: @products,as: "product"

asオプションを設定することで変数名を変更することができます。

これで、部分テンプレートで繰り返し表示ができるようになりました。

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?