[Fixed]-Using a Django variable in a CSS file

11👍

You basically have two options:

  1. Serve your CSS dynamically, with an entry in urls.py, etc., just as if it were an HTML page. Your template file will simply be CSS instead of HTML, but will use normal Django template syntax, etc.

  2. Shortcut: Reference your background image with a relative path. This may or may not be possible for your environment, but it’s a convenient way of having a static CSS file reference different paths depending on where it’s hosted.

14👍

A very good solution here is to use django-compressor. Firstly, if you are serving more than one CSS file, compressor is going to help improve page load times by dropping the number of requests.

A side effect of compressing / concatenating files is that compressor rewrites urls in the css file, so relatively referenced static files (e.g. ../img/logo.png) automatically become fully qualified urls, with the static file url (e.g. http://static.example.com/img/logo.png).

Alternatively you can write custom filters to achieve what you want, or, you can compress your completely static CSS, and some dynamic portions into a single file (for e.g. do this in your base layout file):

{% compress css %}
   <link .... />
   <style>
       .some_rule {background-image:{{MEDIA_URL}}/img/logo.png}
   </style>
{% endcompress %}

This also means you don’t have to worry about efficiency, as the css/js files are generated on first access of a template which uses them, and they are stored as plain files in your static directory (this is configurable), so they are served as normal, static files.

👤Darb

Leave a comment