开发者

Body class for controller in Rails app

Cur开发者_开发技巧rently 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 %>">


The first thing that comes to mind is a layout for that controller. The second thing that comes to mind is a helper that checks the url and applies returns appropriate HTML.

class YourController < ApplicationController
layout "new_layout"
 #...
end


I used @vincent 's way. Since I'm using Rails 5.2.0, before_filter is deprecated and has been replaced with before_action. I made a little change.

controller:

class SomeController < ApplicationController
    before_action do 
        @body_class = 'page'
    end

    ...

end

layout:

<body class="<%= "#{controller.controller_name} #{@body_class}".strip %>">


<body role="document" class="<%= controller.controller_path %> <%= controller.action_name %>" data-controller="<%= controller.controller_path %>" data-action="<%= controller.action_name %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜