Question

I'm a bit new to Rails, so far so good. The assets pipeline/sprockets is pretty neat but I'm a bit confused. When generating scaffolding for my various controllers, individual css/SCSS files were put into app/assets/stylesheets. But for my project I'm using LESS not SCSS, so I replaced them with .css.less files.

The problem I'm running into is that if I add CSS to a controller (let's call it "home.css.less" for example), it gets included in every view, not just views belonging to the "home" controller. If I remove "*= require_tree ." from the application.css file, then the file's not included in any views.

How can I specify CSS code for a particular controller/view using the Rails assets pipeline?

application.css:

/*
  *= require twitter/bootstrap
  *= require_self
  *= require "application_custom"
*/

home.css.less:

body {
  background: asset-url("circles.png") no-repeat;
}

The above results in no background being applied, even to the home controller's views.

Was it helpful?

Solution

This is a fairly common request; many sites have home page specific CSS that they don't want applied over the whole site.

I will make a couple of comments about this before providing the solution, if I may.

The purpose of the pipeline to present one CSS (and one JS) file to clients. The digest is added to allow the addition of server headers that force remote clients to keep a copy of them in their local cache.

The single request and aggressive caching strategy are the default for Rails for performance reasons; each request slows down the page.

Unless the home page CSS is really extensive, I would recommend using the default behavior. If the desire to split this out comes from clashes in CSS selectors between home and other pages, I suggest changing the CSS structure to over come this.

There are at least two common solutions:

The first would be used if you want to manually a different file for each controller.

<%= stylesheet_link_tag "application", controller_name %>

For this to work in production you have to tell rails to precompile all the individual CSS files (in application.rb):

config.assets.precompile << '*.css'

The second is to add a helper to render CSS only when it is required from a view.

I recommend the top solution on this question. You will have to modify the helper names for CSS. That will render a tag for the required CSS only when it set in the view.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top