在 CSS 文件中使用 Django 变量 [英] Using a Django variable in a CSS file

查看:25
本文介绍了在 CSS 文件中使用 Django 变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Django 模板引擎或任何其他方式创建一个 动态 CSS 文件.

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

目前,我有一个如下所示的 CSS 规则:

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

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

其中 http://static.example.com 对应于 Python 中的 STATIC_URL 变量.使用 Django 模板引擎,理论上我可以这样写:

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');

我的问题是,如何使用 Django 模板引擎(或任何其他方式)动态生成 CSS?

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

推荐答案

你基本上有两个选择:

  1. 动态提供您的 CSS,在 urls.py 等中添加一个条目,就好像它是一个 HTML 页面一样.您的模板文件将只是 CSS 而不是 HTML,但将使用普通的 Django 模板语法等.

  1. 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.

快捷方式:使用相对路径引用您的背景图像.这对于您的环境可能可行,也可能不可行,但这是一种让静态 CSS 文件根据托管位置引用不同路径的便捷方式.

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.

这篇关于在 CSS 文件中使用 Django 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆