Session info or variables in layouts

Suppose I have the following:

In layouts/application.rhtml

Title
<%= render(:partial => "shared/navigation_bar") -%>
<%= @content_for_layout -%>

and in the partial (shared/_navigation_bar) I have:

<%= link_to "My Cart", { :controller => "cart", :action => "my_cart" } -%>

My question is…How can I toggle whether the “My Cart” link is shown
depending on if there is anything in the cart?

If I put:

def some_action
@cart = find_cart
…some other code…
end

I can reference this is the partial(which is in the layout) like this:

<% if @cart %>

<%= link_to "My Cart", { :controller => "cart", :action => "my_cart" } -%>
<% end %>

However, if I don’t include the code in EVERY action, there will be an
error for that page. The DRY principle tells me I should not just be
adding the @cart = find_cart code to every dang action on the controller
just so I can have a little logic in the nav bar. So, what is the best
way to do this? The find_cart method is a private method in the
application controller.

Thanks,

Shagy

Hi Shagy,

Put a before_filter at the top of your controller.

before_filter :find_cart, :except => [:index,
:other_actions_you_want_to_exclude]

It’ll run the find_cart action for every action in the controller except
the
ones you tell it not to.

hth,
Bill