在Rails 3中突出显示当前页面的最佳方法?(Best way to highlight current page in Rails 3? — apply a css class to links

编程入门 行业动态 更新时间:2024-10-25 22:32:40
在Rails 3中突出显示当前页面的最佳方法?(Best way to highlight current page in Rails 3? — apply a css class to links conditionally)

对于以下代码:

<%= link_to "Some Page", some_path %>

如何使用current_page?‎ helper方法应用current的css类?

或者如果还有其他更好的方法可用?

For the following code:

<%= link_to "Some Page", some_path %>

How do I apply a css class current using the current_page?‎ helper method?

Or if some other better way is available?

最满意答案

在app / helpers / application_helper.rb中

def cp(path) "current" if current_page?(path) end

在你的意见:

<%= link_to "All Posts", posts_path, class: cp(posts_path) %>

基本上写一个简单的包装。 此外,您可以扩展该方法,以允许通过添加参数应用其他类。 保持意见简洁/干燥。 或者,没有扩展方法,你可以像简单的String插入一样添加额外的类:

<%= link_to "All Posts", posts_path, class: "#{cp(posts_path)} additional_class" %>

In app/helpers/application_helper.rb

def cp(path) "current" if current_page?(path) end

In your views:

<%= link_to "All Posts", posts_path, class: cp(posts_path) %>

Basically write a simple wrapper around it. Additionally you could extend the method to allow additional classes to be applied by adding arguments. Keeps the views concise/dry. Or, without extending the method, you could just do simple String interpolation like so to add additional classes:

<%= link_to "All Posts", posts_path, class: "#{cp(posts_path)} additional_class" %>

更多推荐

本文发布于:2023-08-07 18:37:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465513.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:页面   方法   current   highlight   Rails

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!