Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 - passing variable to partial

I am following the Ruby on Rails tutorial and have come across a problem while trying to pass variables to partials.

My _user partial is as follows

<li>
  <%= gravatar_for user, size: 52 %>
  <%= link_to user.name, user %>
</li>

I would like to pass in a number for the size value. I am trying as follows without any luck.

<%= render @users, :locals => {:size => 30} %>
like image 630
dopplesoldner Avatar asked Apr 26 '13 17:04

dopplesoldner


2 Answers

From the Rails api on PartialRender:

Rendering the default case

If you're not going to be using any of the options like collections or layouts, you can also use the short-hand defaults of render to render partials.

Examples:

# Instead of <%= render partial: "account" %>
<%= render "account" %>

# Instead of <%= render partial: "account", locals: { account: @buyer } %>
<%= render "account", account: @buyer %>

# @account.to_partial_path returns 'accounts/account', so it can be used to replace:
# <%= render partial: "accounts/account", locals: { account: @account} %>
<%= render @account %>

# @posts is an array of Post instances, so every post record returns 'posts/post' on `to_partial_path`,
# that's why we can replace:
# <%= render partial: "posts/post", collection: @posts %>
<%= render @posts %>

So, you can use pass a local variable size to render as follows:

<%= render @users, size: 50 %>

and then use it in the _user.html.erb partial:

<li>
    <%= gravatar_for user, size: size %>
    <%= link_to user.name, user %>
</li>

Note that size: size is equivalent to :size => size.

like image 79
Karim Sonbol Avatar answered Oct 31 '22 22:10

Karim Sonbol


You need the full render partial syntax if you are passing locals

<%= render @users, :locals => {:size => 30} %>

Becomes

<%= render :partial => 'users', :collection => @users, :locals => {:size => 30} %>

Or to use the new hash syntax

<%= render partial: 'users', collection: @users, locals: {size: 30} %>

Which I think is much more readable

like image 22
jamesc Avatar answered Oct 31 '22 21:10

jamesc