Brian
Brian

Reputation: 285

Pass entire array as local variable into partial, then render another partial with collection

I have a layered partial scheme and am trying to write DRY code. I need to pass a variable into a partial and maintain its array status so that within the partial I can render another partial with the :collection parameter.

on this page I render the 'feed' partial:

 %div.row
    %div.span6
      %h1 Posts 
      /Post feed
      =render 'feed',:locals => {:feed_items => @posts}
    %div.span6
      %h1 Groups
      /Group feed
      =render 'feed', :locals => {:feed_items => @groups}

Here is the 'feed' partial:

%ol
  -if feed_items.first.is_a?(Post)
    =render :partial => 'post_feed_item', :collection => feed_items
  -else
    =render :partial => 'group_feed_item', :collection => feed_items
=will_paginate feed_items

Currently gives me this error:

undefined local variable or method `feed_items' for #<#<Class:0x007fa8e2aa8b00>:0x007fa8e5405390>

UPDATE 1:

real error. final partial doesn't recognize component of the :collection passed to it:

undefined local variable or method `feed_item' for #<#<Class:0x007fa8e2aa8b00>:0x007fa8e2c6d670>

final partial 'post_feed_item'(layer 3?):

%li.feed_item.row-fluid
  %div.image.span3
    =link_to image_tag(feed_item.assets.empty?  ? '/assets/small.png': feed_item.assets.first.image.url(:small), :alt => feed_item.title), post_url(feed_item)

So there is some problem in the first partial...feed_items isn't being parsed as an array?

Upvotes: 0

Views: 2283

Answers (2)

jvnill
jvnill

Reputation: 29599

calling

= render partial: 'post_feed_item', collection: feed_items

will give you a post_feed_item local variable and not a feed_item variable. either you use that or pass in an as option to set the local variable name.

= render partial: 'post_feed_item', collection: feed_items, as: :feed_item

Upvotes: 1

Shane Andrade
Shane Andrade

Reputation: 2675

I think you need to render it as a partial:

 %div.row
    %div.span6
      %h1 Posts 
      /Post feed
      =render :partial => 'feed',:locals => {:feed_items => @posts}
    %div.span6
      %h1 Groups
      /Group feed
      =render :partial => 'feed', :locals => {:feed_items => @groups}

Upvotes: 0

Related Questions