Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

python - Using a Django variable in a CSS file

I am trying to create a dynamic CSS file using the Django templating engine or any other means.

Currently, I have a CSS rule that looks like this:

background-image: url('http://static.example.com/example.png');

Where http://static.example.com corresponds to the STATIC_URL variable in Python. Using the Django templating engine, I could theoretically write something like this:

background-image: url('{{ STATIC_URL }}example.png');

My question is, how can I use the Django templating engine (or any other means) to generate CSS dynamically?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...