Django:CSS 在静态文件中引用媒体(django dev / 1.3 / 静态文件)
与 django 用户的任何其他用户一样,我提供静态文件。我选择使用 django-staticfiles 为 django 做好准备1.3 基本上会将其集成到核心中。
我的问题实际上非常简单 - 这非常适合将多个媒体源整合在一起并在 django 模板中以统一的方式引用它们。然而,我经常在 Css 中使用图像背景,如下所示:
#itemname { background-image: url('/path/to/image.png'); }
我的问题很简单 - 如果我使用绝对名称,我必须对它们进行硬编码。如果我使用相对名称,移动到“子目录”url 会弄乱这些项目的资源位置,并且无法加载它们。
那么,如何将这个解决方案扩展到 CSS 呢?上述解决方案必须避免:
- 在 html 中嵌入 css。我个人避免这种情况。
- 使用硬编码网址。这效果不太好,因为在我的本地设置中,我通常使用 'localhost/project' 和 apache 进行测试 (mod_wsgi),而我倾向于使用
project.com
进行部署。
有想法吗?
Like any other user of django user I serve static files. I've chosen to use django-staticfiles to be ready for django 1.3 which will basically integrate it into the core.
My question is pretty simple really - this works great for pulling together multiple media sources and referencing them in a uniform way in django templates. However, I often use image backgrounds in Css like so:
#itemname { background-image: url('/path/to/image.png'); }
My question is simple - if I use absolute names, I have to hard code them. If I use relative names, moving to "subdirectory" urls messes up the resource location for these items and they can't be loaded.
So, how do I extend this solution to CSS? Said solution must avoid:
- Embedding css in html. I personally avoid this.
- Using hardcoded urls. This does not work very well because on my local setup I typically use 'localhost/project' with apache for testing (mod_wsgi) whereas I tend to use
project.com
for deployment.
Ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你说相对路径有问题,但我不明白你的意思。
我遇到了同样的问题,我使用相对路径来解决它。唯一要记住的是,部署图像时需要(显然)保持与 CSS 文件相同的路径。
我的设置简而言之:
注意 我仍在 Django 1.2 中使用 django-staticfiles,但它对于 Django 1.3 的工作方式应该类似
然后我从
提供 CSS {{ STATIC_URL }}css/style.css
引用../images/logo.png
处的图像。我的项目如下所示:
如果您有任何疑问,请告诉我,我会澄清。
You said you had trouble with relative paths, but I don't understand exactly what you meant.
I ran into the same issue, and I've used relative paths to solve it. The only thing to keep in mind is that when deploying the images need to (obviously) remain in the same path relative to the CSS files.
My setup in a nutshell:
Note I'm still using django-staticfiles with Django 1.2, but it should work similarly for Django 1.3
Then I serve the CSS from
{{ STATIC_URL }}css/style.css
which references images at../images/logo.png
.and my project looks like this:
Let me know if you have any questions, and I'll clarify.
好吧,
我不知道@John 的解决方案是否有问题,但它对我不起作用,然后我将此代码放在 CSS 上
,
希望它有帮助!
Ok,
I don't know if there is something wrong with @John's solution but it didn't worked to me then I put this code on the CSS
and
Hope it helps!