PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, May 18, 2022

[FIXED] How to pass variables to partials?

 May 18, 2022     partial, ruby-on-rails     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing