bobblez
bobblez

Reputation: 1370

Correct way of conditional rendering within a partial in Rails?

I have created a partial for a LineItem that, in my case, emits a <tr> with a couple of <td>s. This works just fine and dandy.

What I'd want to do then, is use the same partial in different places. The original view has plenty of room, so displaying every cell is ok. But another (a sidebar), has much less space, and I'd only want to display two of the 5 cells.

So the question, then, is what is the correct way of implementing this? I'd like for the "full" version to be the default unless otherwise specified, and only use the limited version if a parameter is passed.

Currently I'd probably use the feature of passing locals to a partial and check if a parameter limited is defined, and if so, skip the last N cells. Am I on a right track, and if so, what kind of a variable should I use (can I use symbols for this)?

Current _line_item.html.erb (that I'm somewhat unhappy with)

<tr>
  <td><%= line_item.quantity %>&times;</td>
  <td><%= line_item.product.title %></td>
  <td class="item_price"><%= number_to_currency(line_item.total_price, unit: '€') %></td>
  <% unless defined? limited %>
    <td class="remove_item"><%= button_to 'Remove', line_item, method: :delete %></td>
  <% end %>
</tr>

Edit: Added current version.

Upvotes: 0

Views: 406

Answers (1)

Tyler
Tyler

Reputation: 11499

Yes, you are on the right track. You can do something like

<%= render 'partial_name', limited: true %>

and then in the partial:

<% limited ||= false %> # More explicit as to what default value is
<tr>
  <td><%= line_item.quantity %>&times;</td>
  <td><%= line_item.product.title %></td>
  <td class="item_price"><%= number_to_currency(line_item.total_price, unit: '€') %></td>
  <% unless limited %>
    <td class="remove_item"><%= button_to 'Remove', line_item, method: :delete %></td>
  <% end %>
</tr>

Upvotes: 1

Related Questions