Gibson
Gibson

Reputation: 2085

How to pass variables to partials?

I have a common problem that normally I would solve with locals, but this time wont work.

I have the following block:

        <% @user.followers.each do |follower| %>
            <%= render "follower_card" %>
        <% end %>

And the following partial:

<div class="row follower-card">
    <%= image_tag follower.avatar_url(:smallthumb), class: "col-4 inline avatar_medium circle" %>
    <ul class="col-8 inline">
        <li><%= follower.name %></li>
        <li><%= follower.location %></li>
        <li class="lightgray small inline"><span class="bold"><%= follower.photos.count %></span> Spots</li> - 
        <li class="lightgray small inline"><span class="bold"><%= follower.albums.count %></span> Spotbooks</li>
    </ul>
</div>

I'm getting the following error:

undefined local variable or method `follower' for #<#<Class:0x007fe791a4c8d0>:0x007fe799b14b98>

Upvotes: 0

Views: 63

Answers (3)

markets
markets

Reputation: 7043

This should work (specifying the follower variable):

<%= render "follower_card", follower: follower %>

Anyway, I recommend you to use collection rendering for performance reasons. Take a look here: http://guides.rubyonrails.org/layouts_and_rendering.html. Should be something like:

<%= render "follower_card", collection: @user.followers %>

Related question: Render partial :collection => @array specify variable name

Note

Old syntax to pass variables to partials is also valid (verbose, but less elegant IMHO):

<%= render partial: "follower_card", locals: { follower: follower } %>

Upvotes: 4

Jiř&#237; Posp&#237;šil
Jiř&#237; Posp&#237;šil

Reputation: 14412

<%= render "follower_card", follower: follower %>

or

<%= render partial: "follower_card", locals: {follower: follower} %>

Upvotes: 1

Jorge de los Santos
Jorge de los Santos

Reputation: 4643

This is because you are not passing the variable to the partial. The scope of the partial is limited to itself, and you are not making follower available inside. You will have to use:

    <% @user.followers.each do |follower| %>
        <%= render "follower_card", locals: {follower: follower} %>
    <% end %>

Is the proper way.

Upvotes: 2

Related Questions