Wednesday, May 18, 2022

[FIXED] How to pass variables to partials?

Issue

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>

Solution

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 } %>


Answered By - markets
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.