views:

215

answers:

2

I am trying using a partial to render the application's menu, capitalizing the 'tab' using CSS, based on a local variable (tab):

  <%= link_to "employees", jobs_path, :class => (tab=="employees" ? "selected":"unselected") %>
  <a class="unselected">jobs</a>
  <%= link_to "tags", tags_path, :class => (tab=="tags" ? "selected":"unselected") %>

The partial is embedded in the the Application's layout:

<body>
...
<!-- tab variable needs to be set in the view, not the layout -->
<%= render :partial => "layouts/primary_menu", :locals => { :tab => "profiles" } %>
...
</body>

Unfortunately, I need to set the variable's value in the view, but the variable isn't available. Should I be using the :content_for symbol instead of :locals?

At some point, I may want to pass a model instance variable to the partial, so the solution needs to be flexible.

Is there a better approach?

+1  A: 

I think there are multiple ways to handle this, here is one - not necessarily the best

<!-- layout -->
<body>
    <%= yield(:tabs_navigation) %>
    ...
</body>

<!-- views -->
<%- tabs_navigation(render :partial => "layouts/primary_menu", :locals => { :tab => "profiles" }) %>

another way - use a member variable instead of locals (this is kinda like cheating - but effective)

<!-- layout -->
<body>
    <%= render :partial => "layouts/primary_menu" %>
    ....
</body>

<!-- views -->
<%- @current_tab = "profiles" %> 

now access the @current_tab directly in the primary_menu partial

Using content_for

<!-- layout -->
<body>
    <%= yield(:tabs_navigation) %>
    ...
</body>

<!-- views -->
<%- content_for :tabs_navigation do -%>
    <%= render :partial => "layouts/primary_menu", :locals => { :tab => "profiles" } %>
<%- end -%>

http://guides.rubyonrails.org/layouts_and_rendering.html#understanding-yield

house9
Will :content_for work?
Craig
added content_for example; pretty verbose when you just want to change the value of a single variable
house9
A: 

I decided to make use of the link_to_unless_current UrlHelper:

<%= link_to_unless_current "enroll", enroll_path, :class => "unselected" do
    link_to "enroll", enroll_path, :class => "selected"
end %>
Craig