Waldemar Kornewald on August 17, 2010

Using Sass with django-mediagenerator

This is the second post in our django-mediagenerator series. If you haven't read it already, please read the first post before continuing: django-mediagenerator: total asset management

What is Sass?

Great that you ask. :) Sass is a high-level language for generating CSS. What? You still write CSS by hand? "That's so bourgeois." (Quick: Who said that in which TV series?) Totally. ;)

Sass to CSS is like Django templates to static HTML. Sass supports variables (e.g.: $mymargin: 10px ), reusable code snippets, control statements ( @if , etc.), and a more compact indentation-based syntax. You can even use selector inheritance to extend code that is defined in some other Sass file! Also, you can make computations like $mymargin / 2 which can come in very handy e.g. for building fluid grids. Let's see a very simple example of the base syntax:

.content padding: 0 p margin-bottom: 2em .alert color: red

This produces the following CSS code:

.content { padding: 0; } .content p { margin-bottom: 2em; } .content .alert { color: red; }

So, nesting can help reduce repetition and the cleaner syntax also makes Sass easier to type and read. Once you start using the advanced features you won't ever want to go back to CSS. But please do yourself a favor and don't use the ugly alternative SCSS syntax. :)

Do I have to convert my CSS by hand?

Nah, you don't have to do it by hand. One solution is to just go to the css2sass website and paste your CSS code there. The website will convert everything to nice Sass source. Alternatively, you can convert the CSS file using the sass-convert command line tool which comes pre-installed with Sass. Let's pretend you want to convert "style.css" to "style.sass":

sass-convert style.css style.sass

It's that easy.

Yes, I want to use it now!

Enough talk. Let's say you have a Sass file called "css/design.sass" and just for the fun of it you also have a CSS file from a jQuery plugin called "css/jquery.plugin.css". Let's combine everything into a "main.css" bundle:

# settings.py MEDIA_BUNDLES = ( ('main.css', 'css/design.sass', 'css/jquery.plugin.css', ), )

It couldn't be easier. The media generator detects Sass files based on their file extension, so you just have to name the file. But here comes the best part: In your Sass files you can use the handy @import statement to import other files and the media generator will automatically keep track of all dependencies. So, whenever you change one of the dependencies the main Sass file gets recompiled on-the-fly. This is very much like the "sass --watch" development mode, but with the nice advantage that you don't even have to remember to start the Sass command. Barney Stinson would say: "It's legendary!" :)

So, if you want to feel legendary don't wait for it and quickly install Sass and give it a try with django-mediagenerator. It'll boost your CSS productivity to new heights.