Dynamic_CSS_Generation

Quick Profile

Alex Ooi Profile Picture
Hometown: Melbourne, Australia
Specializations: Java, Ruby on Rails
University: Software Engineering & Economics, Melbourne University
High School: VCE, Melbourne High School
Links:
 

Popular Articles

Wednesday, March 16, 2011

Here is an interesting little thing relating to CSS generation...

We've configured a http request interceptor on the server side such that, whenever a request comes in for a CSS resource, the interceptor will kick in and generate CSS from a SASS template and return the contents in a http response, instead of forwarding to the applications controllers. The result is that we don't need to checkin any CSS generated from SASS templates since they are generated "on the fly".

The bit of code looks like what is below... but the same sort of concept could be applied to a java application with a http servlet filter configured for any *.css resources. The servlet filter could then be configured to use node JS to generate CSS from "less css" templates. To avoid re-generation of the content on each request a simple instance variable could be used to cache the results of each "less css" template that has been generated.

Anyway, below is some ruby code that conceptually describes what could be done in a http request filter:


    ....

    stylesheets_dir = File.join(Rails.root, 'app', 'stylesheets')
    load_paths = ["#{stylesheets_dir}"] + 
                  Compass.sass_engine_options[:load_paths]
    css_content = Sass::Engine.new(File.read(template_path), 
                  :syntax => :scss, :load_paths => load_paths).to_css
    return [200, {'Content-Type' => 'text/css', 
                  'Last-Modified' => last_modified_timestamp, css_content]

Load path is important

For the purposes of Compass integration with SASS we would need to include all of the Compass SASS libraries on the load path, otherwise the SASS Engine won't be able to find the functions/mixins that our SASS files require. This caused me a few issues until digging up the helpful "#sass_engine_options" method which conveniently returns all the locations of compass library files :)

The end result of having such a filter ...

... is that you don't end up with duplicated SASS and CSS files in your codebase. You only ever need to maintain SASS files, and CSS files never exist on your filesystem so you can't accidentally check them in and you don't have duplicated code. The excellent thing is that the same principle could easily apply to java web apps :D

Comments ...

Holy Guacamole! Nobody has commented on this post yet! Why don't you make a name for yourself and be the first to do so ... Any comment whatsoever, as long as it is non-defamatory, will be welcome!

Add a Comment

*
*
You must answer the following simple maths question before your comment will be accepted.
*