2

我有一个根据用户所在页面呈现的动态子菜单。我将以下代码放在 _sub_menu.html.erb 部分中:

<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" 部分。我希望通过传入本地参数并根据该参数进行渲染来从渲染中做到这一点,但这似乎很hacky:

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

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

4

2 回答 2

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" %>
于 2010-10-21T14:41:32.207 回答
2

我认为您可以使用 block 参数 to 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' }) %>

那样有用吗?

于 2010-10-21T14:31:01.077 回答