Currently I 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 in any controller where it's set, something like:
class SomeController < ApplicationController
body_class 'page'
...
end
class AnotherController < ApplicationController
body_class 'page'
...
end
Which will result in:
<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 pattern:
<body data-controller="#{controller.controller_path}" data-action="#{controller.action_name}">
Neat! ha?
And then in your document.ready fire whichever JS script you want for that controller-action combination... ( This can be auto-executed on document ready )
All credit goes to: http://viget.com/inspire/extending-paul-irishs-comprehensive-dom-ready-execution
and:
http://blog.jerodsanto.net/2012/02/a-simple-pattern-to-namespace-and-selectively-execute-certain-bits-of-javascript-depending-on-which-rails-controller-and-action-are-active/
My solution:
Controller:
class SomeController < ApplicationController
before_filter lambda { @body_class = 'page' }
...
end
Layout:
<body class="<%= "#{controller.controller_name} #{@body_class}".strip %>">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With