Easy conditional style class names in Rails
How many times do you see something like this?
<%=
link_to("Somewhere", "#",
class: "class-1 class-2#{" class-3" if true}"
)
%>
# <a href="#" class="class-1 class-2 class-3">Somewhere</a>
Gross right!?
Take advantage of a token list instead.
It's also got a great alias in class_names
<%=
link_to("Somewhere", "#",
class: class_names("class-1 class-2", {"class-3": true})
)
%>
# <a href="#" class="class-1 class-2 class-3">Somewhere</a>
As you see it can be passed different types and still generates down to a string list.
It works great with the current_page
helper.
<%=
link_to("Home", root_path,
class: class_names({"active": current_page?(root_path)})
)
%>
# <a href="/" class="active">Home</a>
Tweet