March 5, 2012
by Julia Elman
0 comments
Categories:
Technical

Using LESS with Django

Lately, I’ve been working on creating a simplified work flow for my front end work here at Caktus. There are all sorts of new and helpful tools to optimize the creative process, allowing for faster iterations, and greater overall enjoyment. As with any new tool, there are a few options to choose from: LESS and SASS. Having read lots of reviews and reading through the documentation, I’ve decided LESS is more for me.

LESS provides lots of useful tidbits that you’ve always wanted to do with your style sheets but never imagined possible. For example, variables immediately make your stylesheets less painful to muddle through:

@darkred: #CD0000;

h1 {
   color: @darkred;
}

I love that you can use plain text to map to commonly reused values , making it much easier to remember which is which! This is just the tip of the iceberg when it comes to what you can do with LESS.

Since this post is about work flow, I’ll leave it to the authors to explain how to utilize it over here: http://lesscss.org/

One thing that we struggled with is what our work flow would look like when compiling LESS. Being primarily a Django shop, we decided to use django-compressor to create a seamless way to create, edit, version and deploy our LESS files. Here is an example of how we use it in our templates:

{% load compress %}

{% if debug %}
// This is the client-side way to compile less and an ok choice for local dev
<link rel="stylesheet/less" type="text/css" media="all" href="{{ STATIC_URL }}less/style.less" />
<script src="{{ STATIC_URL }}js/less-1.3.0.min.js"></script>
{% else %}
{% compress css %}
// This is the nifty django-compressor way to compile your less files in css
<link rel="stylesheet" type="text/less" media="all" href="{{ STATIC_URL }}less/style.less" />
{% endcompress %}
{% endif %}

Because the {% if %} statement is only true if DEBUG = True in your settings.py file, which should be your local development setting default anyways, django-compressor will only get to work once your site is deployed to a live or production environment. You can easily keep on saving and editing your LESS files without having to think about. This set-up also helps you get started on your project without having to delve into installing django-compressor or npm locally which is the next step!

The LESS documentation recommends you use node.js in order to get everything running. You’ll need to install npm and then use it to install LESS. Then, install django-compressor and place the following in your settings.py file:

COMPRESS_PRECOMPILERS = (
   ('text/less', 'lessc {infile} {outfile}'),
)
You will also need to set your internal ip to point towards your local environment too:
INTERNAL_IPS = ('127.0.0.1',)

And there you have it! Your LESS file is all ready to automatically compile on your server.

Read more about django-compressor

blog comments powered by Disqus