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

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

问题描述

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

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.

但是,似乎不清楚如何从模板访问 MEDIA_URL,如果我想使用 Django 的机制,它很重要用于加载静态内容.基本上,我的基本模板看起来有点像这样:

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>

上面的代码真的有效吗?我听说你必须使用其他插件来启动和运行这样的东西,这看起来有点奇怪,因为大概定义 MEDIA_URL 背后的重点是在模板中使用它.>

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.

推荐答案

要访问模板中的 STATIC_URL,请确保 django.core.context_processors.staticcode>TEMPLATE_CONTEXT_PROCESSORS,并且您正在使用 RequestContext.更多详情这里.

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.

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

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天全站免登陆