I would like to implement a dynamic class name to a navigation pane in Rails.
To do that, I defined an attribute in my controller like this:
class StoresController < ApplicationController
@nav = "store"
def index
...
end
end
And then, I use the @nav attribute in my application.html.erb file like this:
<%= link_to "Store", stores_path, if @nav == 'store' { :class => 'selected' } %>
But it doesn’t work. I tried other combinations like using link_to with () or inverting if syntax, but nothing works.
My question: How do you dynamically set class value in Rails? What are best practices?
Thanks in advance.
@nav is a controller class instance variable not a controller object instance variable and it is not visible in your action and corresponding templates.
I’m assuming that you want to depend on current controller, so you could do something like this:
The best practice for me is to create a helper which depending on your current path and given path returns apropriate class name or even whole link (link_to replacement in this case).