在 CSS 文件中使用 Django 变量
我正在尝试使用 Django 模板引擎或任何其他方式创建动态 CSS 文件。
目前,我的 CSS 规则如下所示:
background-image: url('http://static.example.com/example.png');
其中 http://static.example.com
对应于 Python 中的 STATIC_URL
变量。使用 Django 模板引擎,理论上我可以编写如下内容:
background-image: url('{{ STATIC_URL }}example.png');
我的问题是,如何使用 Django 模板引擎(或任何其他方式)动态生成 CSS?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一个非常好的解决方案是使用 django-compressor。首先,如果您要提供多个 CSS 文件,压缩器将通过减少请求数量来帮助缩短页面加载时间。
压缩/连接文件的副作用是压缩器重写了css文件中的url,因此相对引用的静态文件(例如../img/logo.png)自动成为完全限定的url,静态文件url(例如http://static.example.com/img/logo.png)。
或者,您可以编写自定义过滤器来实现您想要的效果,或者,您可以将完全静态的 CSS 和一些动态部分压缩到单个文件中(例如,在您的基本布局文件中执行此操作):
这也意味着您没有担心效率,因为 css/js 文件是在第一次访问使用它们的模板时生成的,并且它们作为普通文件存储在静态目录中(这是可配置的),因此它们作为普通的静态文件提供。
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):
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.
您基本上有两个选择:
动态地提供 CSS,在 urls.py 等中包含一个条目,就像它是一个 HTML 页面一样。您的模板文件将只是 CSS 而不是 HTML,但将使用普通的 Django 模板语法等。
快捷方式:使用相对路径引用您的背景图像。这对于您的环境来说可能可行,也可能不可能,但这是一种让静态 CSS 文件根据其托管位置引用不同路径的便捷方法。
You basically have two options:
Serve your CSS dynamically, with an entry in urls.py, etc., just as if it were an HTML page. Your template file will simply be CSS instead of HTML, but will use normal Django template syntax, etc.
Shortcut: Reference your background image with a relative path. This may or may not be possible for your environment, but it's a convenient way of having a static CSS file reference different paths depending on where it's hosted.