The body class for the controller in a Rails application
I currently have this in my layout:
<body class="<%= controller.controller_name %>"> I want to add an additional class that will be the same for all actions on any controller where it is installed, something like:
class SomeController < ApplicationController body_class 'page' ... end class AnotherController < ApplicationController body_class 'page' ... end This will lead to:
<body class="some page"> <body class="another page"> What would be the easiest way to achieve this? Can I use controller class variables for this?
Stop! Stop! Use this template:
<body data-controller="#{controller.controller_path}" data-action="#{controller.action_name}"> Well maintained! ha?
And then in your document. Already shoot any JS script that you want for this combination of controller actions ... (This can be done automatically when the document is ready)
All loans go to: http://viget.com/inspire/extending-paul-irishs-comprehensive-dom-ready-execution
and
I used @Vincent. Since I am using Rails 5.2.0, before_filter deprecated and has been replaced with before_action . I made a small change.
controller:
class SomeController < ApplicationController before_action do @body_class = 'page' end ... end location:
<body class="<%= "#{controller.controller_name} #{@body_class}".strip %>">