问题
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!
Edit: Ok, my bad. What I meant was, how do let users customize their page if they wanted to? I suppose I could have done this without using external stylesheet, but I think CSS is served fastest if it's static and on a CDN and not using a template and CPU resources to render. Please guide me if there's a way to achive this.
回答1:
That's not the way to do this sort of thing. You should define different classes in the CSS file, then use then in your template dependent on the variables there.
回答2:
This is a old question but I thought I'd help others as I also wanted to do this and I found a solution.
Instead of using a normal link tag specifying your stylesheet, use style tags and include your css file inline.
<style>{% include 'my.css' %}</style>
Then you can put jinja code in your css file and it will render the variables. Useful if you want to allow users to customize colors etc.
回答3:
I agree with Daniel Roseman's answer, but if you -really- need to do this you can just define your CSS in the template and use the python variable as shown there.
Another option is to see if you can use mako templating if you can get it to work with Django.
But, unless you have some unusual compelling reason you need to do this, define your own CSS classes.
回答4:
you can pass the css style attribute adding the following line in your html page.
<div class="profile-cover" style="background: url('{{ cover }}')">
added attribute to css class provile-cover style="background: url('{{ cover }}')"
{{ cover }} is the variable rendered from views.py to the HTML page using the urls.py
来源:https://stackoverflow.com/questions/18431948/passing-variables-to-css-file-in-django