在Rails中动态添加活动类到bootstrap li
在引导程序导航栏中。 您可以通过添加active
类来获得单击按钮的效果。 当然,我想在我的网页上使用它。 例如,如果我在关于我们页面,我想点击关于我们按钮。
最好的方法是什么? 我打算去每个页面,并在底部有一个jQuery函数添加active
的类。 有没有更好的办法?
了解current_page?
这里
您可以使用current_page?
为句柄逻辑添加方法current_page?
,示例方法:
module ApplicationHelper def active_class(link_path) current_page?(link_path) ? "active" : "" end end
示例引导程序导航栏模板
所以,在视图上看起来像
HTML
<%= link_to "text of link", some_path %>
HAML
%li{:class => active_class(some_path)} = link_to "text of link", some_path
或者,如果当前路径具有参数,则可以使用request.fullpath
获取当前的完整路径
例
<% Contry.all.each do |c| %> - <%= link_to "show #{c.name}", contry_path(c) %>
<% end %>
并在您的application_helper.rb
def active_class(link_path) request.fullpath == link_path ? "active" : "" end
在这里阅读request.fullpath
在我看来,更link_to_in_li
方法是在application_helper.rb中编写一个link_to_in_li
方法:
def link_to_in_li(body, url, html_options = {}) active = "active" if current_page?(url) content_tag :li, class: active do link_to body, url, html_options end end
然后以这种方式使用它
<%= link_to_in_li "Home", root_path, id: "home_link" %>
我发现里面的代码有点难以阅读。
对于任何理解这一点的人来说,这里有一个示例,我的路径和文件名明确地布局。 作为一个相当新的铁杆人,我很难搞清楚。 感谢上面回答的其他人,因为它帮助我解决了问题!
我将Bootstrap导航栏放在我的application.html.erb文件中:
这包含在application_helper.rb文件中:
module ApplicationHelper def is_active?(link_path) current_page?(link_path) ? "active" : "" end end
而已! 现在,您的应用程序将动态地将“活动”类添加到当前正在查看的任何页面(即,它是导航栏中的相应列表项)。 这比手动向每个页面(视图)添加导航栏然后更新“活动”类要简单得多(并且更干)。
我将根据这些其他人发布我创建的答案,因为在CRUD视图的情况下,未放置活动类。
module ApplicationHelper def active_class(name) controller_name.eql?(name) || current_page?(name) ? 'active' : '' end end
我的观点使用这样的东西:
请在每个页面中尝试此操作,检查cotroller或操作并添加css
例如:
><%= link_to 'my page', pages_path%>
您可以在application_helper.rb
定义一个辅助方法
def create_link(text, path) class_name = current_page?(path) ? 'active' : '' content_tag(:li, class: class_name) do link_to text, path end end
现在你可以使用:
create_link 'xyz', any_path
将呈现为
完美的自举导航!
为什么只限制li
元素? 为什么不支持多个类名和active
? 这个解决方案让我:
- 不仅支持纯文本,还支持
link_to
HTML(例如,在链接中添加一个图标) - 只需几行代码即可添加到
application_helper.rb
- 将
active
附加到link元素的整个类名,而不是它是唯一的类。
所以,将它添加到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
在您的模板上,您可以使用以下内容:
<%= link_to root_path, :class => active_class?("btn btn-outline-primary", root_path) do %> <% end %>
您还可以指定或不指定class_name
并像这样使用它:
Home
感谢先前的答案1,2和资源 。