Passing variables to css file in django

1,730 views
Skip to first unread message

Robin Lery

unread,
Aug 25, 2013, 1:55:37 PM8/25/13
to django...@googlegroups.com
Is it possible to pass variables in css files, like in html file. Example:


In views.py:

    def home(request):
        bgcolor = "#999"
        ...
        ...

In the css file:

    body {
        background-color : {{bgcolor}};
    }


If yes, can you please guide me how to achieve this? I would really appreciate. Thank you!

Andy McKay

unread,
Aug 25, 2013, 8:09:48 PM8/25/13
to django...@googlegroups.com
Any string can be rendered as a template. This is covered pretty well in the docs:

https://docs.djangoproject.com/en/dev/ref/templates/api/

For example:

>>> from django.template import Context, Template
>>> t = Template("body { background-color: {{ bgcolor }} }")
>>> c = Context({'bgcolor': '#999'})
>>> t.render(context=c)
u'body { background-color: #999 }'

However, CSS is served fastest if it's static and on a CDN and not using a template and CPU resources to render.

Robin Lery

unread,
Aug 25, 2013, 10:08:11 PM8/25/13
to django...@googlegroups.com
Oh! I am sorry. What I meant was, how do I let users customize their page if they wanted to? I suppose I could have done this without using external stylesheet, but yes, CSS is served fastest if it's static. I hope, I made myself clear. Please guide me if there's a way to achive this


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
For more options, visit https://groups.google.com/groups/opt_out.

Chris Lawlor

unread,
Aug 26, 2013, 12:42:19 PM8/26/13
to django...@googlegroups.com
The simplest solution is probably to keep all of the CSS that users can't customize in an external file (to be served as a static asset), but move anything that's user customizable to the <head> of your base template, in a <style> tag. You'd probably want to implement some sort of caching for user style preferences, assuming these won't be changing often.

Giulio Calacoci

unread,
Aug 27, 2013, 9:10:52 AM8/27/13
to django...@googlegroups.com
May I suggest to save user defined css to a file saved in a specific path?

for example if user John_Doe submits a customized css, save it in /<server_path_to_static_files>/css/users/john_doe/override.css

then in the head of the html file load the user defined css always after the default one.

this way is always static, and the result is cleaner than any <style> tag...

my two cents.

regards

Giulio.
-- 
 Giulio Calacoci - 2ndQuadrant Italia
 PostgreSQL Training, Services and Support
 giulio....@2ndQuadrant.it | www.2ndQuadrant.it 
Reply all
Reply to author
Forward
0 new messages