by
back

optional local variables in a ruby on rails partial

In ruby on rails you can use partials to DRY up your views.

/app/views/items/_item.html.erb

<div class="item">
    <h3><%= item.name %></h3>
    <p><%= item.description %></p>
</div>

You now can render the partial like this

app/view/items/index.html.erb

<% @items.each do |item| %>
    <%= render "items/item", :item => item %>
<% end %>

<% @items.each do |item| %>
    <%= render item %>
<% end %>

<%= render @items %>

Each of these options will result in the same output.

We can pass variables to a partial as seen in the first option. We can use that feature to customize the output of the partial.

app/view/items/index.html.erb

<% @items.each do |item| %>
    <%= render item, display_description: true %>
<% end %>

/app/views/items/_item.html.erb

<div class="item">
    <h3><%= item.name %></h3>
    <% if display_description %>
        <p><%= item.description %></p>
    <% end %>
</div>

If you pass parameters to a partial then you should define default values for that parameter in your partial. Otherwise you always have to set the parameters to avoid problems with nil values:

/app/views/items/_item.html.erb

<% display_description = false if local_assigns[:display_description].nil? %>
<% display_description = local_assigns.fetch :display_description, false %>
<% display_description ||= false %>
<div class="item">
    <h3><%= item.name %></h3>
    <% if display_description %>
        <p><%= item.description %></p>
    <% end %>
</div>

There are some ways to set default values in your partial. The first option checks the local_assigns hash for the given key.
The second options uses the fetch method with the optional default_value.
The third option sets the default value if the current value is nil or false.



comments powered by Disqus