CSS文件中的Django媒体URL [英] Django media URLs in CSS files

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

问题描述

在django模板中,通常执行以下操作:

 < img src ={{MEDIA_URL}} / IMG / someImage.jpg> 

您将如何在不作为模板的CSS文件中完成此工作?

  .someClass {
/ *不能这样做* /
background:url({{MEDIA_URL} } /img/someImage.jpg);
/ *这个* /
背景:url(http://media.domain.com/img/someImage.jpg);
/ *或这个* /
background:url(/ django_static_media / img / someImage.jpg);
/ *不能同时做两件事呢? * /
}

我需要能够从媒体子域,或在离线工作期间直接将其作为django静态视图提供。但CSS文件是一个问题,因为它们不作为模板处理,我不能使用 MEDIA_URL 上下文变量。



什么是解决方案?



编辑:我应该注意到,由于我的静态媒体文件实际上位于单独的媒体子

解决方案

你在哪里提供的css文件?这通常不是常见的媒体结构问题,例如:

  media / 
images /
css /
js /

(或类似)允许图像的相对文件路径,例如:

  background:url('../ images / foo.png'); 

如果您不准备更改媒体文件夹结构以适应相对文件路径,则可能没有其他选择,只能从模板中覆盖css声明,在离线时使用辅助css文件:

  {%if DEBUG%} 
< link rel =stylesheethref ={{MEDIA_URL}} css / offline-mode.css/>
{%endif%}

当然第一个选项比较整洁。 >

In django templates, it's common to do the following:

<img src="{{ MEDIA_URL }}/img/someImage.jpg">

How would you accomplish this in a CSS file which is not served as a template?

.someClass {
    /* can't do this this */
    background: url("{{ MEDIA_URL }}/img/someImage.jpg");        
    /* either this */
    background: url("http://media.domain.com/img/someImage.jpg");
    /* or this */
    background: url("/django_static_media/img/someImage.jpg");
    /* can't do both... what to do? */
}

I need the ability to serve my files either from the media subdomain, or during offline work and serve them directly as a django static view. But CSS files are a problem since they are not processed as templates and I cannot use the MEDIA_URL context variable.

What's the solution?

Edit: I should note that the problem arises since my static media files are in fact located on a separate media sub-domain, thus negating the use of relative paths. Got it, thanks!

解决方案

Where is your css file served from? This usually isn't a problem as a common media structure such as:

media/
    images/
    css/
    js/

(or similar) allows for relative file paths for images, eg:

background: url('../images/foo.png');

If you're not prepared to change your media folder structure to accommodate relative file paths, you may have no alternative but to overwrite css declarations from within the template, using a secondary css file when offline:

{% if DEBUG %}
    <link rel="stylesheet" href="{{ MEDIA_URL }}css/offline-mode.css" />
{% endif %}

Of course the first option is much tidier.

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

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