Search code examples
djangodjango-templatesdynamic-css

How to render a template with dynamic CSS?


I want to create a dynamic CSS file in a view and then render a template which loads that CSS file. Depending on the arguments given to the view, the CSS may have different values at certain places every time the view is called. How would I go about doing that? (I should add that I have no experience with writing files in Python/Django.)

Here is a simplified example of how I think it should work:

# urls.py
urlpatterns = patterns('',
    (r'^myview/(?P<color>[0-9a-f]{6})/$', create_css_file),
)

# views.py
def create_css_file(request, color):
    raw = "@charset 'UTF-8';\n\n"
    raw += "body {\n"
    raw += "  color: #" + color + ";\n"
    raw += "}\n\n"

    f = open('mydynamic.css', 'r+')
    f.write(raw)

    return render_to_response('mytemplate.html', locals())

# mytemplate.html
{% extends "base.html" %}
{% block head %}
    <link rel="stylesheet" media="screen" href="{{ f.name }}" />
{% endblock %}

For some reason, that doesn't work, although in the resulting HTML page's source code, it looks like the CSS file is loaded correctly. The f even arrives at the template correctly, because I can see its contents when I change the <link>... line to

<link rel="stylesheet" media="screen" href="{{ f }}" />

(finstead of f.name). But the HTML is rendered without the desired color setting. Can anybody tell my why that is?

I suspected some path issue, and I toyed around quite a bit with different paths, but to no avail.

Please do not advise me to prepare several hardcoded CSS files (as I have found in answers to similar questions), because there will be several hundred possibilities.


Solution

  • I went with @CatPlusPlus's suggestion: Calculating the necessary values in a view and passing the template a very long string (raw) which contains the entire CSS. In the template, I include it like so:

    <style media="screen">{{ raw|safe }}</style>
    

    Thanks everyone for your efforts!