...

/

Hiding an Empty Cart with a Custom Helper

Hiding an Empty Cart with a Custom Helper

Learn to add different checks to the cart by using custom helper methods.

Hiding empty cart

The customer has one last request. Right now, even carts with nothing in them are displayed in the sidebar. Can we arrange for the cart to appear only when it has some content? But of course!

In fact, we have a number of options. The simplest is to include the HTML for the cart only if the cart has something in it. We can do this completely within the _cart partial:

Press + to interact
<% unless cart.line_items.empty? %>
<h2>Your Cart</h2>
<table>
<%= render(cart.line_items) %>
<tr class="total_line">
<td colspan="2">Total</td>
<td class="total_cell"><%= number_to_currency(cart.total_price) %></td>
</tr>
</table>
<%= button_to 'Empty cart', cart, method: :delete, confirm: 'Are you sure?' %>
<% end %>

Although this works, the code is a bit odd. Our application layout is rendering a cart partial, which then turns around and avoids rendering anything if the cart is empty. It would be cleaner if the application layout had the logic for ...