rails 5 bootstrap 4(单个控制器)中的索引操作不同 css

different css for index action in rails 5 bootstrap 4 (single controller)

我正在为我的应用程序使用特定的 bootstrap 4 模板。此模板 (cover.css) 特定于主页,因为所有其他页面将使用不同的样式。

如何才能将 cover.css 仅用于索引操作?

在我的 application.css 中添加了 @import "cover" 我可以只将其应用于索引操作吗?

我尝试创建两个布局:application.html.erb 用于应用程序,第二个布局 home.html.erb 仅用于主页。我如何才能仅将 cover.css 关联到 index 操作,并将我的仪表板布局和 css 关联到应用程序的其余部分?

我正在使用 rails 5 和 bootstrap 4 alpha。

像这样的东西会起作用。

<%= stylesheet_link_tag    "application", :media => "all" %>
<%= stylesheet_link_tag params[:controller] %>

在这里查看第三个答案:How do I use Controller specific stylesheets in Rails 3.2.1?

有几种方法可以做到这一点。

您可以创建一个包含 cover.css 资产的布局,然后仅按此处所述为索引操作应用布局 Rails layouts per action?

class MyController < ApplicationController
  layout :resolve_layout

  # ...

  private

  def resolve_layout
    case action_name
    when "new", "create"
      "some_layout"
    when "index"
      "other_layout"
    else
      "application"
    end
  end
end

另一种选择是使用单一布局并确定样式范围。

views/layouts/application.html.erb中像这样在正文标签上设置类

<body class="<%= controller_name %> <%= action_name %>"> 渲染时它会输出 <body class="home index">

然后在您的 cover.css 中将您的样式范围限定为 .home.index 选择器

body.home.index h1{
    /* this style is only applied on the home/index page */
}