我有一个根据用户所在页面呈现的动态子菜单。我将以下代码放置在 _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'} %>
而且逻辑变得非常丑陋。有更好的方法吗?
最佳答案
您可以定义一个额外的辅助方法,该方法将调用 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" %>
关于ruby-on-rails - 在 Rails 3 的菜单部分中渲染事件菜单元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3988404/