Body class for controller in Rails app

耗尽温柔 提交于 2019-12-05 01:50:01

问题


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?


回答1:


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/




回答2:


My solution:

Controller:

class SomeController < ApplicationController

  before_filter lambda { @body_class = 'page' }

...

end

Layout:

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



回答3:


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



回答4:


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 %>">



回答5:


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


来源:https://stackoverflow.com/questions/4555632/body-class-for-controller-in-rails-app

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