Joe Marion
Joe Marion

Reputation: 406

Most efficient place to link stylesheets in rails

I have been debating asking this for some time now, but am still not quite sure the appropriate place to link a stylesheet. I have no problem getting stylesheets to work, but I want to know what is the official "railsy" way to do it. Do you link all of your stylesheets in the application.html?

When I create a new view, or view directory I might create a stylesheet that will contain all the styles for that directory. If there are more elaborate pages within the directory I may create multiple stylesheets, one for each page. Now is it appropriate to just link to these styles within the application layout, or have it loaded only when the view is loaded using a stylesheet_link_tag?

When I try to have the styles loaded per page load it seems more sluggish, but it just doesn't feel right having every stylesheet have to load by including all of them in the application layout.

How do you link your stylesheets?

Upvotes: 0

Views: 174

Answers (1)

dpedoneze
dpedoneze

Reputation: 959

You can use the content_for to add those styles and set them inside each view.

application.html.haml

%html
  %head
    %title YOUR_APP
    = stylesheet_link_tag 'application', media: 'all'
    = yield :stylesheet

application/home/index.scss

h2 {
  color: blue;
}

home/index.html.haml

= content_for :stylesheet, stylesheet_link_tag("application/home/index")


%h2
  My home index

application.scss

@import 'base/base';
@import 'modules/module';

Then, it will only load when you hit the home#index page. Normally we add all the common css inside application.scss (@import '..' or *= require ...) and only the most specific view css we add using the content_for.

Upvotes: 1

Related Questions