This Rails plugin provides a template helper which identifies relevant stylesheets and links them to the page. Following the principle of convention over configuration, stylesheets may be organized and implicitly included based on controller name and principle template name.
This plugin is designed for Rails 2.3. I have made no effort for its usefulness to previous versions in this edition. You will find, I think, a working Rails 2.2 version in the history of this repository.
Just check the plugin out into your application’s
/vendor/plugins directory. I suggest using the git submodule approach:
git submodule add git://github.com/ajtack/css_auto_include.git vendor/plugins/css_auto_include
Remember: when you clone a separate repository, you must call
git submodule init and
git submodule update to actually populate submodules.
This plugin does some modification of the ApplicationController and ActionView::Base classes to make its usage almost transparent. As long as the layout and application controller base class are set up (two quick steps), the detection of CSS files by name is automatic.
Add the following line to
Modify Your Layouts
<head> tag in each page is probably in your layout. Add the following line where you would like the stylesheet link tags included:
<%= css_auto_include_tags %>
This line will include up to three stylesheets from
public/stylesheets, in the following order:
Suppose we have a Rails application which sells books, CDs, and blankets. When we’re looking at an individual blanket, we want to have a special layout so that customers can see close-ups of the fabric. Similarly, when we do anything with books, we have extra CSS which displays a preview of the book’s text. To support these style requirements separately, we fill our
public/stylesheets directory with the following:
application.css(the general site layout)1
books.css(our style for all actions of the books controller)
showaction of the
In the default layout for our application (
layouts/application.html.erb), we add a call to the
css_auto_include_tags method as below.
... <head> <title>My Amazing Shop</title> <meta name="author" content="Joe Blow" /> <%= css_auto_include_tags %> </head> ...
Now, when we navigate to the url
/cds/, we get our application stylesheet and nothing extra. If we navigate to anything under
/books/, we also get our books-specific stylesheet. Lastly, whenever we look at a particular blanket item (say, at the url
/blankets/1/), we get only
blankets/show.css. All the other blanket views get
Andres Jaan Tack©2009 firstname.lastname@example.org
1 Currently, it does not matter which particular layout you employ; the stylesheet is always application.css. I haven’t had a reason thus far to make this layout-specific, but it seems like it shouldn’t be too bad.