1

I am using a specific bootstrap 4 template for my application. This template (cover.css) is specific to the homepage as all the others pages will use a different style.

How can I use cover.css only for the index action?

In my application.css I added @import "cover" can I have this only applied to the index action?

I tried creating two layouts instead: application.html.erb to use it for the application, and a second layout home.html.erb just for the home page. How can I associate cover.css for only the index action and have my dashboard layout and css for the rest of the application?

I am using rails 5 and bootstrap 4 alpha.

Ayrad
  • 3,996
  • 8
  • 45
  • 86

2 Answers2

2

There are a few ways to accomplish this.

You can create a layout which includes the cover.css asset, and then only apply the layout for the index action as described here 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

Another option would be to use a single layout and scope your styles.

In views/layouts/application.html.erb Set classes on the body tag like this

<body class="<%= controller_name %> <%= action_name %>"> When rendered it will output <body class="home index">

Then in your cover.css scope your styles to the .home.index selector

body.home.index h1{
    /* this style is only applied on the home/index page */
}
Community
  • 1
  • 1
Jason Yost
  • 4,807
  • 7
  • 42
  • 65
  • which of these options do you think is more of a best practices kind of solution? – Ayrad Oct 10 '16 at 06:49
  • Both of them are acceptable as best practices. You could use both solutions together. In this case, if it's only CSS that you need to be different, then I would say just scope the styles. If you need the layout to be entirely different, then of course use the resolve layout method. – Jason Yost Oct 10 '16 at 16:37
1

Something like this will work.

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

See the 3rd answer here: How do I use Controller specific stylesheets in Rails 3.2.1?

Community
  • 1
  • 1
Paul W
  • 226
  • 3
  • 5