Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Body class for controller in Rails app

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?

like image 716
Vincent Avatar asked Dec 02 '22 04:12

Vincent


2 Answers

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/

like image 167
luigi7up Avatar answered Dec 04 '22 04:12

luigi7up


My solution:

Controller:

class SomeController < ApplicationController

  before_filter lambda { @body_class = 'page' }

...

end

Layout:

<body class="<%= "#{controller.controller_name} #{@body_class}".strip %>">
like image 32
Vincent Avatar answered Dec 04 '22 04:12

Vincent