Alex Rivera | Logout

Django media URLs in CSS files

Asked 2009-06-21T13:25:35.090
39

In django templates, it's common to do the following:

<img src="{{ MEDIA_URL }}/img/someImage.jpg">

How would you accomplish this in a CSS file which is not served as a template?

.someClass {
    /* can't do this this */
    background: url("{{ MEDIA_URL }}/img/someImage.jpg");        
    /* either this */
    background: url("http://media.domain.com/img/someImage.jpg");
    /* or this */
    background: url("/django_static_media/img/someImage.jpg");
    /* can't do both... what to do? */
}

I need the ability to serve my files either from the media subdomain, or during offline work and serve them directly as a django static view. But CSS files are a problem since they are not processed as templates and I cannot use the MEDIA_URL context variable.

What's the solution?

Edit: I should note that the problem arises since my static media files are in fact located on a separate media sub-domain, thus negating the use of relative paths. Got it, thanks!

Edit
Report

3 Answers

50

Where is your css file served from? This usually isn't a problem as a common media structure such as:

media/
    images/
    css/
    js/

(or similar) allows for relative file paths for images, eg:

background: url('../images/foo.png');

If you're not prepared to change your media folder structure to accommodate relative file paths, you may have no alternative but to overwrite css declarations from within the template, using a secondary css file when offline:

{% if DEBUG %}
    <link rel="stylesheet" href="{{ MEDIA_URL }}css/offline-mode.css" />
{% endif %}

Of course the first option is much tidier.

answered 2009-06-21T13:48:59.223
3

Is using relative paths (for image files) in your CSS files not a viable option for you?

answered 2009-06-21T13:50:09.250
0

If you want to use template directives in a file, why isn't it served via a template?

answered 2009-06-21T14:08:56.420

Your Answer