"> ...">

The body class for the controller in a Rails application

I currently 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 on any controller where it is installed, something like:

 class SomeController < ApplicationController body_class 'page' ... end class AnotherController < ApplicationController body_class 'page' ... end 

This will lead to:

 <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?

+4
source share
5 answers

My decision:

Controller:

 class SomeController < ApplicationController before_filter lambda { @body_class = 'page' } ... end 

Markup:

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

Stop! Stop! Use this template:

 <body data-controller="#{controller.controller_path}" data-action="#{controller.action_name}"> 

Well maintained! ha?

And then in your document. Already shoot any JS script that you want for this combination of controller actions ... (This can be done automatically when the document is ready)

All loans go 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 /

+10
source

The first thing that comes to mind is the layout for this controller. The second thing that comes to mind is the helper, which checks the URL and applies returns the appropriate HTML code.

 class YourController < ApplicationController layout "new_layout" #... end 
+1
source

I used @Vincent. Since I am using Rails 5.2.0, before_filter deprecated and has been replaced with before_action . I made a small change.

controller:

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

location:

 <body class="<%= "#{controller.controller_name} #{@body_class}".strip %>"> 
0
source
 <body role="document" class="<%= controller.controller_path %> <%= controller.action_name %>" data-controller="<%= controller.controller_path %>" data-action="<%= controller.action_name %> 
-2
source

Source: https://habr.com/ru/post/1333693/


All Articles