Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Exclude Some Stylesheets in Rails 4

Rails 4 uses asset pipeline to concatenate and minify or compress JavaScript and CSS assets. It creates a default app/assets/stylesheets/application.css file which contains these lines:

/*
*= require_self
*= require_tree .
*/

The require_tree directive tells Sprockets to recursively include all CSS files in the specified directory into the output.

There are times that for some layout pages that we would like to exclude a couple of CSS files. Following two ways help us to accomplish this:

Build separate directives for these two different layouts. Suppose there are one set of CSS files for front landing page, move thos specific files to app/assets/stylesheets/landing; For the other pages, move their CSS files to app/assets/stylesheets/content. Finally move all common/shared ones to app/assets/stylesheets/common

Then edit the three manifest files:

/*
 * application-common.css
 *
 *= require_self
 *= require_tree ./common
 */
/*
 * application-landing.css
 *
 *= require_self
 *= require_tree ./landing
 */
/*
 * application-content.css
 *
 *= require_self
 *= require_tree ./content
 */

Also you will need to set in config:

config.assets.precompile += %w( application-common.css application-landing.css application-content.css )  

Use Rails 4 keyword If for example, landing page just needs one special CSS file, using approach above seems to be an overkill. All we need is to exclude this one file from the rest pages and on landing page, add it. We could use stub keyword, provided by Rails 4.

/*
 * application.css
 *
 *= require_self
 *= require_tree .
 *= stub 'landing'
 */

That application.css loads all CSS files except landing.css.

Then in the landing page markup, we add:

<%= stylesheet_link_tag  'landing' %>  

Also don't forget to set in config/initializers/assets.rb

Rails.application.config.assets.precompile += %w( landing.css )  

With all this, we achieve our goal of only landing page loads landing.css file, while others intact.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment