Body class for controller in Rails app

喜你入骨 提交于 2019-12-03 17:31:05

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 %>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!