添加“当前”的最佳方式Rails 3 中的类到导航

发布于 2024-09-19 07:43:56 字数 369 浏览 3 评论 0原文

我的导航菜单中有一些静态页面。我想向当前显示的项目添加一个像“current”这样的类。

我这样做的方法是添加大量的辅助方法(每个方法对应一个项目)来检查控制器和操作。

def current_root_class
  'class="current"' if controller_name == "homepage" && action_name == "index" 
end

<ul>
  <li <%= current_root_class %>><%= link_to "Home", root_path %>

还有更好的办法吗!?我现在的做法实在是太愚蠢了……

I have some static pages in a navigation menu. I want to add a class like "current" to the item which is currently displaying.

The way I am doing so is to add tons of helper methods (each for one item) to check the controller and action.

def current_root_class
  'class="current"' if controller_name == "homepage" && action_name == "index" 
end

<ul>
  <li <%= current_root_class %>><%= link_to "Home", root_path %>

Is there any better way to do so!? My current way is so stupid......

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(24

熊抱啵儿 2024-09-26 07:43:56

我制作了一个名为 nav_link 的助手:

def nav_link(link_text, link_path)
  class_name = current_page?(link_path) ? 'current' : ''

  content_tag(:li, :class => class_name) do
    link_to link_text, link_path
  end
end

使用方式如下:

nav_link 'Home', root_path

它将生成类似的 HTML

<li class="current"><a href="/">Home</a></li>

I made a helper called nav_link:

def nav_link(link_text, link_path)
  class_name = current_page?(link_path) ? 'current' : ''

  content_tag(:li, :class => class_name) do
    link_to link_text, link_path
  end
end

used like:

nav_link 'Home', root_path

which will produce HTML like

<li class="current"><a href="/">Home</a></li>
浅笑依然 2024-09-26 07:43:56

使用 current_page? 帮助器以确定是否应该分配 "current" 类。例如:

<%= 'active' if current_page?(home_about_path) %>

请注意,您还可以传递路径(不仅仅是选项的哈希值),例如:current_page?(root_path)

Use the current_page? helper to determine whether or not you should assign the "current" class. For example:

<%= 'active' if current_page?(home_about_path) %>

Note you can also pass a path (not only a hash of options), e.g: current_page?(root_path).

幸福丶如此 2024-09-26 07:43:56

这里并不是真正的答案,因为我使用的方式与你完全相同。我刚刚定义了辅助方法来测试多个控制器或操作:

在 application_helper.rb 中

  def controller?(*controller)
    controller.include?(params[:controller])
  end

  def action?(*action)
    action.include?(params[:action])
  end

然后您可以使用 if controller?("homepage") && action?("index", "show") 在你的视图或其他辅助方法中......

Not truly an answer here, because I'm using quite the same way as you are. I've just defined helper methods to test for multiple controller or actions:

In application_helper.rb

  def controller?(*controller)
    controller.include?(params[:controller])
  end

  def action?(*action)
    action.include?(params[:action])
  end

Then you can use if controller?("homepage") && action?("index", "show") in your views or other helper methods…

守护在此方 2024-09-26 07:43:56

我在 application_helper.rb (Rails 3) 中使用这个 nav_link(text, link) 函数来完成工作,它会为我滚动我的 bootstrap twitter 2.0 导航栏链接。

def nav_link(text, link)
    recognized = Rails.application.routes.recognize_path(link)
    if recognized[:controller] == params[:controller] && recognized[:action] == params[:action]
        content_tag(:li, :class => "active") do
            link_to( text, link)
        end
    else
        content_tag(:li) do
            link_to( text, link)
        end
    end
end

例子:

<%=nav_link("About Us", about_path) %>

I use this nav_link(text, link) function in application_helper.rb (Rails 3) to get the job done and it rolls my bootstrap twitter 2.0 nav bar links for me.

def nav_link(text, link)
    recognized = Rails.application.routes.recognize_path(link)
    if recognized[:controller] == params[:controller] && recognized[:action] == params[:action]
        content_tag(:li, :class => "active") do
            link_to( text, link)
        end
    else
        content_tag(:li) do
            link_to( text, link)
        end
    end
end

Example:

<%=nav_link("About Us", about_path) %>
南渊 2024-09-26 07:43:56

我这样做的方法是在 application_helper 中添加一个辅助函数

def current_class?(test_path)
  return 'current' if request.request_uri == test_path
  ''
end

,然后在导航中,

<%= link_to 'Home', root_path, :class => current_class?(root_path) %>

这会根据当前页面 uri 测试链接路径,并返回当前类或空字符串。

我还没有对此进行彻底的测试,而且我对 RoR 还很陌生(在使用 PHP 十年后才转向),所以如果这有一个重大缺陷,我很乐意听到它。

至少这样你只需要 1 个辅助函数和每个链接中的一个简单调用。

The way I've done it is to add a helper function in the application_helper

def current_class?(test_path)
  return 'current' if request.request_uri == test_path
  ''
end

Then in the nav,

<%= link_to 'Home', root_path, :class => current_class?(root_path) %>

This tests the link path against the current page uri and returns either your current class or an empty string.

I've not tested this thoroughly and I'm very new to RoR (moving over after a decade with PHP) so if this has a major flaw I'd love to hear it.

At least this way you only need 1 helper function and a simple call in each link.

小猫一只 2024-09-26 07:43:56

为了构建@Skilldrick的答案...

如果您将此代码添加到application.js,它将确保任何具有活动子项的下拉菜单也将被标记为活动...

$('.active').closest('li.dropdown').addClass('active');

回顾一下支持代码>添加一个名为 nav_link:

def nav_link_to(link_text, link_path)
  class_name = current_page?(link_path) ? 'active' : ''

  content_tag(:li, :class => class_name) do
    link_to link_text, link_path
  end
end

used like:

nav_link_to 'Home', root_path

的帮助器,它将生成类似的 HTML

<li class="active"><a href="/">Home</a></li>

To build off @Skilldrick 's answer...

If you add this code to application.js it will make sure that any dropdown menus with active children will also be marked as active...

$('.active').closest('li.dropdown').addClass('active');

To recap supportive code > Add a helper called nav_link:

def nav_link_to(link_text, link_path)
  class_name = current_page?(link_path) ? 'active' : ''

  content_tag(:li, :class => class_name) do
    link_to link_text, link_path
  end
end

used like:

nav_link_to 'Home', root_path

which will produce HTML like

<li class="active"><a href="/">Home</a></li>
满栀 2024-09-26 07:43:56

我认为最好的方法是

application_helper.rb:

def is_active(controller, action)       
  params[:action] == action && params[:controller] == controller ? "active" : nil        
end

在菜单中:

<li class="<%= is_active('controller', 'action') %>">

I think the best way is

application_helper.rb:

def is_active(controller, action)       
  params[:action] == action && params[:controller] == controller ? "active" : nil        
end

And in menu:

<li class="<%= is_active('controller', 'action') %>">
烟织青萝梦 2024-09-26 07:43:56

我知道这是一个过时的答案,但是您可以使用名为 的 link_to 帮助器包装器轻松忽略所有这些当前页面检查active_link_to gem,它完全按照你想要的方式工作,将活动类添加到当前页面链接

I know it is a out dated answer, but you can easily ignore all these current page check by using a link_to helper wrapper, called active_link_to gem, it works exactly what you want, add a active class to current page link

弥繁 2024-09-26 07:43:56

这是完整的示例,介绍如何在 Rails 视图的引导菜单页面上添加活动类。

    <li class="<%= 'active' if current_page?(root_path) %>"><%= link_to 'Home', controller: "welcome" %></li>
    <li class="<%= 'active' if current_page?(about_path) %>"><%= link_to 'About us', about_path %></li>
   <li class="<%= 'active' if current_page?(contact_path) %>"><%= link_to 'Contact us', contact_path %></li>

Here is the full example, on how to add an active class on bootstrap menu page in rails view.

    <li class="<%= 'active' if current_page?(root_path) %>"><%= link_to 'Home', controller: "welcome" %></li>
    <li class="<%= 'active' if current_page?(about_path) %>"><%= link_to 'About us', about_path %></li>
   <li class="<%= 'active' if current_page?(contact_path) %>"><%= link_to 'Contact us', contact_path %></li>
天邊彩虹 2024-09-26 07:43:56

我使用一个名为 Tabs on Rails 的很棒的 gem。

I use an awesome gem called Tabs on Rails.

执手闯天涯 2024-09-26 07:43:56

我有一个更简洁的 nav_link 版本,其工作方式与 link_to 完全相同,但经过定制以输出包装 li 标记。

将以下内容放入 application_helper.rb

def nav_link(*args, &block)
    if block_given?
      options      = args.first || {}
      html_options = args.second
      nav_link(capture(&block), options, html_options)
    else
      name         = args[0]
      options      = args[1] || {}
      html_options = args[2]

      html_options = convert_options_to_data_attributes(options, html_options)
      url = url_for(options)

      class_name = current_page?(url) ? 'active' : nil

      href = html_options['href']
      tag_options = tag_options(html_options)

      href_attr = "href=\"#{ERB::Util.html_escape(url)}\"" unless href
      "<li class=\"#{class_name}\"><a #{href_attr}#{tag_options}>#{ERB::Util.html_escape(name || url)}</a></li>".html_safe
    end
  end

如果您查看上面的代码并将其与 url_helper.rb 中的 link_to 代码进行比较,唯一的区别是它检查 url 是否是当前页面,并将类“active”添加到一个包装 li 标签。这是因为我将 nav_link 帮助器与 Twitter Bootstrap 的 nav 组件 一起使用,它更喜欢链接被包装在 li 标签内,“active”类应用于外部 li。

上面代码的好处是它允许您将块传递到函数中,就像使用 link_to 一样。

例如,带有图标的引导导航列表如下所示:

Slim:

ul.nav.nav-list
  =nav_link root_path do
    i.icon-home
    |  Home
  =nav_link "#" do
    i.icon-user
    |  Users

输出:

<ul class="nav nav-list">
  <li class="active">
    <a href="/">
      <i class="icon-home"/>
      Home
    </a>
  </li>
  <li>
    <a href="#">
      <i class="icon-users"/>
      Users
    </a>
  </li>
</ul>

此外,就像 link_to 帮助器一样,您可以将 HTML 选项传递到 nav_link 中,该选项将应用于 a 标记。

为锚点传递标题的示例:

Slim:

ul.nav.nav-list
  =nav_link root_path, title:"Home" do
    i.icon-home
    |  Home
  =nav_link "#", title:"Users" do
    i.icon-user
    |  Users

输出:

<ul class="nav nav-list">
  <li class="active">
    <a href="/" title="Home">
      <i class="icon-home"/>
      Home
    </a>
  </li>
  <li>
    <a href="#" title="Users">
      <i class="icon-users"/>
      Users
    </a>
  </li>
</ul>

I have a more succinct version of nav_link that works exactly like link_to, but is customized to output a wrapping li tag.

Put the following in your application_helper.rb

def nav_link(*args, &block)
    if block_given?
      options      = args.first || {}
      html_options = args.second
      nav_link(capture(&block), options, html_options)
    else
      name         = args[0]
      options      = args[1] || {}
      html_options = args[2]

      html_options = convert_options_to_data_attributes(options, html_options)
      url = url_for(options)

      class_name = current_page?(url) ? 'active' : nil

      href = html_options['href']
      tag_options = tag_options(html_options)

      href_attr = "href=\"#{ERB::Util.html_escape(url)}\"" unless href
      "<li class=\"#{class_name}\"><a #{href_attr}#{tag_options}>#{ERB::Util.html_escape(name || url)}</a></li>".html_safe
    end
  end

If you look at the above code and compare it to the link_to code in url_helper.rb, the only difference is that it checks if the url is the current page, and adds the class "active" to a wrapping li tag. This is because I'm using the nav_link helper with Twitter Bootstrap's nav component which prefers links to be wrapped inside li tags and the "active" class applied to the outer li.

The nice thing about the above code is that it allows you to pass in a block into the function, just like you can do with link_to.

For example, a bootstrap nav list with icons would look like:

Slim:

ul.nav.nav-list
  =nav_link root_path do
    i.icon-home
    |  Home
  =nav_link "#" do
    i.icon-user
    |  Users

Output:

<ul class="nav nav-list">
  <li class="active">
    <a href="/">
      <i class="icon-home"/>
      Home
    </a>
  </li>
  <li>
    <a href="#">
      <i class="icon-users"/>
      Users
    </a>
  </li>
</ul>

In addition, just like the link_to helper, you can pass in HTML options into nav_link, which will be applied to the a tag.

An example of passing in a title for the anchor:

Slim:

ul.nav.nav-list
  =nav_link root_path, title:"Home" do
    i.icon-home
    |  Home
  =nav_link "#", title:"Users" do
    i.icon-user
    |  Users

Output:

<ul class="nav nav-list">
  <li class="active">
    <a href="/" title="Home">
      <i class="icon-home"/>
      Home
    </a>
  </li>
  <li>
    <a href="#" title="Users">
      <i class="icon-users"/>
      Users
    </a>
  </li>
</ul>
ゃ人海孤独症 2024-09-26 07:43:56

就我个人而言,我在这里使用了答案的组合

<li class="<%= 'active' if current_page?(inventory_index_path) %>"><a href="#">Menu</a></li>

,我使用的是 Materialize CSS,我使主要类别可折叠的方法是使用下面的代码

$('.active').closest(".collapsible.collapsible-accordion")
            .find(".collapsible-header")
            .click();

希望它可以帮助某人

For me personally i used a combination of answers here

<li class="<%= 'active' if current_page?(inventory_index_path) %>"><a href="#">Menu</a></li>

I am using materialize css and my way of making the main categories collapsible is by using the code below

$('.active').closest(".collapsible.collapsible-accordion")
            .find(".collapsible-header")
            .click();

hope it helps someone

鲜血染红嫁衣 2024-09-26 07:43:56

current_page? 方法对我来说不够灵活(假设你设置了一个控制器而不是一个操作,那么它只会在控制器的索引操作上返回 true),所以我做了这个基于关于其他答案:

  def nav_link_to(link_text, link_path, checks=nil)
    active = false
    if not checks.nil?
      active = true
      checks.each do |check,v|
        if not v.include? params[check]
          active = false
          break
        end
      end
    end

    return content_tag :li, :class => (active ? 'active' : '') do
      link_to link_text, link_path
    end
  end

示例:

nav_link_to "Pages", pages_url, :controller => 'pages'

The current_page? method isn't flexible enough for me (say you set a controller but not an action, then it'll only return true on the controller's index action), so I've made this based on the other answers:

  def nav_link_to(link_text, link_path, checks=nil)
    active = false
    if not checks.nil?
      active = true
      checks.each do |check,v|
        if not v.include? params[check]
          active = false
          break
        end
      end
    end

    return content_tag :li, :class => (active ? 'active' : '') do
      link_to link_text, link_path
    end
  end

Example:

nav_link_to "Pages", pages_url, :controller => 'pages'
夏末的微笑 2024-09-26 07:43:56

是的!查看这篇文章:将“选定”类添加到 Rails 中的链接的更好方法

将 nav_link_helper.rb 放入 app/helpers 中,它可以像以下一样简单:

<%= nav_link 'My_Page', 'http://example.com/page' %>

nav_link 帮助程序的工作方式与标准 Rails link_to 帮助程序类似,但如果满足某些条件,则将“选定”类添加到您的链接(或其包装器)中都满足了。默认情况下,如果链接的目标 url 与当前页面的 url 相同,则会向链接添加默认类“selected”。

这里有一个要点: https://gist.github.com/3279194

更新:这现在是一个宝石:http://rubygems.org/gems/nav_link_to

Yep! Check out this article: A Better Way to Add a ‘selected’ Class to Links in Rails

Drop nav_link_helper.rb into app/helpers and it can be as easy as:

<%= nav_link 'My_Page', 'http://example.com/page' %>

The nav_link helper works just like the standard Rails link_to helper, but adds a 'selected' class to your link (or its wrapper) if certain criteria are met. By default, if the link's destination url is the same url as the url of the current page, a default class of 'selected' is added to the link.

There's a gist here: https://gist.github.com/3279194

UPDATE: This is now a gem: http://rubygems.org/gems/nav_link_to

多彩岁月 2024-09-26 07:43:56

我使用像这样的简单助手作为顶级链接,因此 /stories/my-story 页面突出显示 /stories 链接

def nav_link text, url

  active = (url == request.fullpath || (url != '/' && request.fullpath[0..(url.size-1)] == url))

  "<li#{ active ? " class='selected'" : '' }><a href='#{url}'>#{text}</a></li>".html_safe

end

I use a simple helper like this for top level links so the /stories/my-story page highlights the /stories link

def nav_link text, url

  active = (url == request.fullpath || (url != '/' && request.fullpath[0..(url.size-1)] == url))

  "<li#{ active ? " class='selected'" : '' }><a href='#{url}'>#{text}</a></li>".html_safe

end
£冰雨忧蓝° 2024-09-26 07:43:56

让我展示我的解决方案:

_header.html.erb:

  <ul class="nav">
    <%= nav_tabs(@tabs) %> 
  </ul>

application_helper.rb:

 def nav_tabs(tabs=[])
    html = []
    tabs.each do |tab| 
      html << (content_tag :li, :class => ("current-page" if request.fullpath.split(/[\??]/)[0] == tab[:path]) do
        link_to tab[:path] do
          content_tag(:i, '', :class => tab[:icon]) +
          tag(:br) +
          "#{tab[:name]}"
        end
      end)        
    end

    html.join.html_safe
  end

application_controller.rb:

before_filter :set_navigation_tabs

private
def set_navigation_tabs
  @tabs = 
    if current_user && manager?
      [
        { :name => "Home", :icon => "icon-home", :path => home_index_path },
        { :name => "Portfolio", :icon => "icon-camera", :path => portfolio_home_index_path },
        { :name => "Contact", :icon => "icon-envelope-alt", :path => contact_home_index_path }
      ]
    elsif current_user && client?
      ...
    end

Let me show my solution:

_header.html.erb:

  <ul class="nav">
    <%= nav_tabs(@tabs) %> 
  </ul>

application_helper.rb:

 def nav_tabs(tabs=[])
    html = []
    tabs.each do |tab| 
      html << (content_tag :li, :class => ("current-page" if request.fullpath.split(/[\??]/)[0] == tab[:path]) do
        link_to tab[:path] do
          content_tag(:i, '', :class => tab[:icon]) +
          tag(:br) +
          "#{tab[:name]}"
        end
      end)        
    end

    html.join.html_safe
  end

application_controller.rb:

before_filter :set_navigation_tabs

private
def set_navigation_tabs
  @tabs = 
    if current_user && manager?
      [
        { :name => "Home", :icon => "icon-home", :path => home_index_path },
        { :name => "Portfolio", :icon => "icon-camera", :path => portfolio_home_index_path },
        { :name => "Contact", :icon => "icon-envelope-alt", :path => contact_home_index_path }
      ]
    elsif current_user && client?
      ...
    end
一张白纸 2024-09-26 07:43:56

根据Skilldrick的回答,我将其更改为以下内容:

def nav_link(*args, &block)
  is_active = current_page?(args[0]) || current_page?(args[1])
  class_name = is_active ? 'active' : nil

  content_tag(:li, class: class_name) do
    link_to *args, &block
  end
end

使其更有用。

According to the answer by Skilldrick, I'll change it to the following:

def nav_link(*args, &block)
  is_active = current_page?(args[0]) || current_page?(args[1])
  class_name = is_active ? 'active' : nil

  content_tag(:li, class: class_name) do
    link_to *args, &block
  end
end

to make it much more useful.

天邊彩虹 2024-09-26 07:43:56

此版本基于@Skilldrick 的版本,但允许您添加 html 内容。

因此,您可以执行:

nav_link "A Page", a_page_path

还可以:

nav_link a_page_path do
  <strong>A Page</strong>
end

或任何其他 html 内容(例如,您可以添加图标)。

这里的助手是:

  def nav_link(name = nil, options = nil, html_options = nil, &block)
    html_options, options, name = options, name, block if block_given?
    options ||= {}

    html_options = convert_options_to_data_attributes(options, html_options)

    url = url_for(options)
    html_options['href'] ||= url

    class_name = current_page?(url) ? 'current' : ''
    content_tag(:li, :class => class_name) do  
      content_tag(:a, name || url, html_options, &block)
    end
  end

This version is based on @Skilldrick's one but allows you to add html content.

Thus, you can do:

nav_link "A Page", a_page_path

but also:

nav_link a_page_path do
  <strong>A Page</strong>
end

or any other html content (you can add an icon for instance).

Here the helper is:

  def nav_link(name = nil, options = nil, html_options = nil, &block)
    html_options, options, name = options, name, block if block_given?
    options ||= {}

    html_options = convert_options_to_data_attributes(options, html_options)

    url = url_for(options)
    html_options['href'] ||= url

    class_name = current_page?(url) ? 'current' : ''
    content_tag(:li, :class => class_name) do  
      content_tag(:a, name || url, html_options, &block)
    end
  end
旧瑾黎汐 2024-09-26 07:43:56

我想我想出了一个简单的解决方案,可能对很多用例都有帮助。这让我:

  • 不仅支持纯文本,还支持 link_to 内的 HTML(例如,在链接内添加图标)
  • 将几行代码添加到 application_helper.rb
  • 附加 active 到链接元素的整个类名,而不是它是唯一的类。

因此,将其添加到 application_helper.rb 中:

def active_class?(class_name = nil, path)
  class_name ||= ""
  class_name += " active" if current_page?(path)
  class_name.strip!
  return class_name
end

在你的模板上你可以有这样的东西:

<div class="col-xs-3">
  <%= link_to root_path, :class => active_class?("btn btn-outline-primary", root_path) do %>
    <i class="fa fa-list-alt fa-fw"></i>
  <% end %>
</div>

作为奖励,您可以指定或不指定class_name并像这样使用它:

感谢之前的回答12资源

I think I came up with a simple solution that might be helpful for a lot of use cases. This lets me:

  • Support not only plain text but HTML inside link_to (e.g. add an icon inside the link)
  • Add just few lines of code to application_helper.rb
  • Append active to the whole class name of the link element instead of it being the sole class.

So, add this to application_helper.rb:

def active_class?(class_name = nil, path)
  class_name ||= ""
  class_name += " active" if current_page?(path)
  class_name.strip!
  return class_name
end

And on your template you can have something like this:

<div class="col-xs-3">
  <%= link_to root_path, :class => active_class?("btn btn-outline-primary", root_path) do %>
    <i class="fa fa-list-alt fa-fw"></i>
  <% end %>
</div>

As bonus you can specify or not a class_name and use it like this: <div class="<%= current_page?(root_path) %>">

Thanks to previous answers 1, 2 and resources.

半寸时光 2024-09-26 07:43:56

ApplicationHelper 中创建一个方法,如下所示。

def active controllers, action_names = nil
  class_name = controllers.split(",").any? { |c| controller.controller_name == c.strip } ? "active" : ""
  if class_name.present? && action_names.present?
    return action_names.split(",").any? { |an| controller.action_name == an.strip } ? "active" : ""
  end
  class_name
end

现在在视图中使用它,如下用例。

1. 对于任何特定控制器的所有操作

<li class="<%= active('controller_name')%>">
....
</li>

2. 对于许多控制器的所有操作(以逗号分隔)

<li class="<%= active('controller_name1,controller_name2')%>">
....
</li>

3. 对于任何特定控制器的特定操作

<li class="<%= active('controller_name', 'action_name')%>">
....
</li>

4. 对于许多控制器的特定操作(以逗号分隔)

<li class="<%= active('controller_name1,controller_name2', 'action_name')%>">
....
</li>

5 .对于任何特定控制器的一些特定操作

<li class="<%= active('controller_name', 'index, show')%>">
....
</li>

6.对于许多控制器的一些特定操作(以逗号分隔)

<li class="<%= active('controller_name1,controller_name2', 'index, show')%>">
....
</li>

希望有帮助

Create a method in ApplicationHelper as below.

def active controllers, action_names = nil
  class_name = controllers.split(",").any? { |c| controller.controller_name == c.strip } ? "active" : ""
  if class_name.present? && action_names.present?
    return action_names.split(",").any? { |an| controller.action_name == an.strip } ? "active" : ""
  end
  class_name
end

Now use it in view as below use cases.

1. For all action of any specific controller

<li class="<%= active('controller_name')%>">
....
</li>

2. For all action of many controllers (with comma seperated)

<li class="<%= active('controller_name1,controller_name2')%>">
....
</li>

3. For specific action of any specific controller

<li class="<%= active('controller_name', 'action_name')%>">
....
</li>

4. For specific action of many controllers (with comma seperated)

<li class="<%= active('controller_name1,controller_name2', 'action_name')%>">
....
</li>

5. For some specific actions of any specific controller

<li class="<%= active('controller_name', 'index, show')%>">
....
</li>

6. For some specific actions of many controllers (with comma seperated)

<li class="<%= active('controller_name1,controller_name2', 'index, show')%>">
....
</li>

Hope it helps

念三年u 2024-09-26 07:43:56

所有这些都适用于简单的导航栏,但是下拉子菜单怎么样?
当选择子菜单时,顶部菜单项应设为“当前”
在这种情况下 tabs_on_rails 我就是解决方案

all these work with simple nav bars, but what about drop down sub-menu ?
when a sub-menu is selected the top menu item should be made 'current'
in this case tabs_on_rails me be the solution

世界等同你 2024-09-26 07:43:56

这就是我在当前项目中解决的方法。

def class_if_current_page(current_page = {}, *my_class)
    if current_page?(current_page)
      my_class.each do |klass|
        "#{klass} "
      end
    end
  end

然后..

li = link_to company_path 
    class: %w{ class_if_current_page( { status: "pending" }, "active" ), "company" } do  
      Current Company

This is how I solved in my current project.

def class_if_current_page(current_page = {}, *my_class)
    if current_page?(current_page)
      my_class.each do |klass|
        "#{klass} "
      end
    end
  end

Then..

li = link_to company_path 
    class: %w{ class_if_current_page( { status: "pending" }, "active" ), "company" } do  
      Current Company
不羁少年 2024-09-26 07:43:56

我的简单方法 -

application.html.erb

<div class="navbar">
    <div class="<%= @menu1_current %> first-item"><a href="/menu1"> MENU1 </a></div>
    <div class="<%= @menu2_current %>"><a href="/menu2"> MENU2 </a></div>
    <div class="<%= @menu3_current %>"><a href="/menu3"> MENU3 </a></div>
    <div class="<%= @menu4_current %> last-item"><a href="/menu4"> MENU4 </a></div>
</div>

main_controller.erb

class MainController < ApplicationController
    def menu1
        @menu1_current = "current"
    end

    def menu2
        @menu2_current = "current"
    end

    def menu3
        @menu3_current = "current"
    end

    def menu4
        @menu4_current = "current"
    end
end

谢谢。

My easy way -

application.html.erb,

<div class="navbar">
    <div class="<%= @menu1_current %> first-item"><a href="/menu1"> MENU1 </a></div>
    <div class="<%= @menu2_current %>"><a href="/menu2"> MENU2 </a></div>
    <div class="<%= @menu3_current %>"><a href="/menu3"> MENU3 </a></div>
    <div class="<%= @menu4_current %> last-item"><a href="/menu4"> MENU4 </a></div>
</div>

main_controller.erb,

class MainController < ApplicationController
    def menu1
        @menu1_current = "current"
    end

    def menu2
        @menu2_current = "current"
    end

    def menu3
        @menu3_current = "current"
    end

    def menu4
        @menu4_current = "current"
    end
end

Thanks.

谁许谁一生繁华 2024-09-26 07:43:56

如果您还想在视图中支持 html 选项哈希。例如,如果你想用其他 CSS 类或 id 来调用它,你可以像这样定义辅助函数。

def nav_link_to(text, url, options = {})
  options[:class] ||= ""
  options[:class] += " active"
  options[:class].strip!
  link_to text, url, options
end

因此,在视图中,以与调用 link_to helper 相同的方式调用此 helper

<%= nav_link_to "About", about_path, class: "my-css-class" %>

If also you want to support html options hash in the view. For example if you want to call it with other CSS class or id, you can define the helper function like this.

def nav_link_to(text, url, options = {})
  options[:class] ||= ""
  options[:class] += " active"
  options[:class].strip!
  link_to text, url, options
end

So in the view, call this helper the same way you'd call link_to helper

<%= nav_link_to "About", about_path, class: "my-css-class" %>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文