目前,我有这个在我的布局:
<body class="<%= controller.controller_name %>">
我想添加一个额外的类,这将是在任何控制器的所有动作,其中它的设置,像相同的:
class SomeController < ApplicationController
body_class 'page'
...
end
class AnotherController < ApplicationController
body_class 'page'
...
end
这将导致:
<body class="some page">
<body class="another page">
什么是实现这一目标的最简单的方法?我可以使用控制器类变量吗?
停止!停止!使用这种模式:
<body data-controller="#{controller.controller_path}" data-action="#{controller.action_name}">
整齐!哈?
然后在哪个JS脚本要用于该控制器的动作组合,你的document.ready火...(这可以是自动执行的文件上的准备)
一切归功于:http://viget.com/inspire/extending-paul-irishs-comprehensive-dom-ready-execution
和:
我的解决方案:
控制器:
class SomeController < ApplicationController
before_filter lambda { @body_class = 'page' }
...
end
布局:
<body class="<%= "#{controller.controller_name} #{@body_class}".strip %>">
,想到的第一件事是该控制器的布局。我想到的第二件事情是检查URL和应用的回报相应的HTML帮手。
class YourController < ApplicationController
layout "new_layout"
#...
end
我用@vincent的方式。由于我使用Rails 5.2.0,before_filter
已被弃用,并已替换为before_action
。我做了一个变化不大。
控制器:
class SomeController < ApplicationController
before_action do
@body_class = 'page'
end
...
end
布局:
<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 %>