LoginSignup
15
14

More than 5 years have passed since last update.

Railsでナビゲーションの現在地をアクティブにする

Posted at

現在いるページのナビゲーションメニューのみに.activeとかcssを適用したいとき、いつもこう書いてる。
ただなんかもっと良い書き方ないかなーと思っているので、誰か良い案ある方いれば教えて下さい :disappointed_relieved:

application.html.erb
<ul class="nav">
  <li class="<%= active_class_for('controller1') %>"><a href="#">Controller1</a></li>
  <li class="<%= active_class_for('controller2') %>"><a href="#">Controller2</a></li>
  <li class="<%= active_class_for('controller3') %>"><a href="#">Controller3</a></li>
</ul>
application_helper.rb
module ApplicationHelper
  def active_class_for controller_name
    'active' if params[:controller] == controller_name
  end
end
15
14
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
14