2010-10-21 35 views
2

我有一个动态子菜单,根据用户所在的页面显示。我把下面的代码在_sub_menu.html.erb部分:渲染菜单中的一个活动菜单元素部分在rails 3中

<a href="/dashboard/index" class="current">Index</a> 
<a href="/dashboard/account">Account</a> 
<a href="/dashboard/payments">Payments</a>` 

从我我的主视图,我称之为<%= render 'sub_menu' %>,它的工作原理。

但是,我想根据用户所在的页面更改class =“current”部分。我希望通过传递局部参数,并根据该渲染渲染做到这一点,但它似乎哈克:

<%= render 'sub_menu' , :locals => {:active_item => 'payments'} %>

加上逻辑变得很丑陋。有没有更好的方法来做到这一点?

回答

2

我想你可以使用块参数link_to_unless_current,它提供的内容呈现在链路是当前页面:

<%= link_to_unless_current("Index", :action => 'index') { link_to("Index", {:action => 'index'}, {:class => 'current' }) %> 
<%= link_to_unless_current("Account", :action => 'account') { link_to("Account", {:action => 'account'}, {:class => 'current' }) %> 
<%= link_to_unless_current("Payments", :action => 'payments') { link_to("Payments", {:action => 'payments'}, {:class => 'current' }) %> 

运作的?

2

您可以定义一个额外的辅助方法,将被调用link_to_unless_current

def link_to_current_with_class(name, current_class, options = {}, html_options = {}, &block) 
    link_to_unless_current(name, options, html_options) do 
    options[:class] = current_class + " " + options[:class] 
    link_to(name, options, html_options) 
    end 
end 

,然后从你的导航部分称之为:

<%= link_to_current_with_class "Index", "current", "/dashboard/index" %>