Passing variables to CSS file in Django

扶醉桌前 提交于 2021-02-09 07:31:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!