Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
532 views
in Technique[技术] by (71.8m points)

ruby - Best way to highlight current page in Rails 3? -- apply a css class to links conditionally

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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" %>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...