如何从Django模板中获取MEDIA_URL? [英] How can I get the MEDIA_URL from within a Django template?

查看:469
本文介绍了如何从Django模板中获取MEDIA_URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于Django如何使用静态内容,我有些困惑。本质上,在 settings.py 文件中,我们定义了 MEDIA_URL ,它指向在解析静态媒体时使用的URL作为脚本和样式,以及 MEDIA_ROOT ,这是对文件系统所在的位置的引用。



但是,我似乎无法从模板中访问 MEDIA_URL 如果我想使用Django的机制来加载静态内容,那么请重要的是/ em> 。本质上,我的基本模板看起来像这样:

 < html> 
< head>
{%block styles%}
< link rel =stylesheethref ={{MEDIA_URL}} styles / master.css/>
{%endblock%}
< title> {%block title%}页面标题{%endblock%}< / title>
< / head>
< body>
{%block scripts%}
< script type =text / javascriptsrc ={{MEDIA_URL}} scripts / jquery.js>< / script>
{%endblock%}
< / body>
< / html>

上述代码是否真的有效?我听说你必须使用其他插件来获得这样的东西,这似乎是一种奇怪的事情,因为大概在定义 MEDIA_URL 之后的一切就是使用在模板中。

解决方案

要访问您的模板中的 STATIC_URL 确实 django.core.context_processors.static TEMPLATE_CONTEXT_PROCESSORS 中,而您正在使用的RequestContext 。更多详情这里



此外,静态文件应放在 STATIC_URL 之下,而不是 MEDIA_URL ,除非是用户上传的内容。


I'm somewhat confused as to how Django operates with static content. Essentially, in the settings.py file, we define MEDIA_URL which points to the URL to use when resolving static media such as scripts and styles, as well as MEDIA_ROOT, a reference to where things live on the filesystem.

However, it doesn't seem clear how I can get access to MEDIA_URL from a template, and it's kind-of-important if I want to use Django's mechanism for loading static content at all. Essentially, I have my base template looking somewhat like this:

<html>
   <head>
       {% block styles %}
       <link rel="stylesheet" href="{{ MEDIA_URL }}styles/master.css"/>
       {% endblock %}
       <title>{% block title %}Page Title{% endblock %}</title>
   </head>
   <body>
      {% block scripts %}
      <script type="text/javascript" src="{{ MEDIA_URL }}scripts/jquery.js"></script>
      {% endblock %}
   </body>
</html>

Will the above code actually work? I've heard that you have to use other plugins to get something like this up and running, which seems kind of strange, as presumably the whole point behind defining MEDIA_URL is to use it in templates.

解决方案

To access STATIC_URL in your templates, make sure django.core.context_processors.static is in TEMPLATE_CONTEXT_PROCESSORS, and that you're using a RequestContext. More details here.

In addition, static files should be placed under STATIC_URL, not MEDIA_URL, unless it is user-uploaded content.

这篇关于如何从Django模板中获取MEDIA_URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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