【问题标题】:Rendering an active menu element in a menu partial in rails 3在rails 3中的部分菜单中呈现活动菜单元素
【发布时间】:2013-08-04 15:49:13
【问题描述】:

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

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

从我的主要观点来看,我打电话给&lt;%= render 'sub_menu' %&gt;,这很有效。

但是,我想根据用户所在的页面更改 class="current" 部分。我希望通过传入本地参数并根据该参数进行渲染来从渲染中做到这一点,但这似乎很hacky:

&lt;%= render 'sub_menu' , :locals =&gt; {:active_item =&gt; 'payments'} %&gt;

加上逻辑变得非常丑陋。有更好的方法吗?

【问题讨论】:

    标签: ruby-on-rails menu partials


    【解决方案1】:

    您可以定义一个额外的辅助方法,即调用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" %>
    

    【讨论】:

      【解决方案2】:

      我想你可以利用link_to_unless_current的block参数,它提供了当链接是当前页面时要呈现的内容:

      <%= 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' }) %>
      

      这行得通吗?

      【讨论】:

        猜你喜欢
        • 2016-12-22
        • 1970-01-01
        • 1970-01-01
        • 2014-04-06
        • 1970-01-01
        • 1970-01-01
        • 2013-01-31
        • 1970-01-01
        • 2014-09-21
        相关资源
        最近更新 更多