【问题标题】:Can't use {{MEDIA_URL}} in Django Flatpages?不能在 Django Flatpages 中使用 {{MEDIA_URL}}?
【发布时间】:2013-07-15 09:13:39
【问题描述】:

一个相当简单的问题,如果需要,我会详细说明以解决问题。

我尝试使用对 {{ MEDIA_URL }} 的简单调用来在 About Us Django 平面页面上显示图像,但该平面页面似乎忽略了它是 Django 变量这一事实,而只是将 {{MEDIA_URL}} 作为文本?

我提供了:<img src="{{ MEDIA_URL }}images/static/Deb-and-Diana-About-Us.jpg" alt="Deb & Diana Portrait" width="300" height="384" align="left">,但是当模板被渲染时,它并没有在它应该附加的地方添加 MEDIA_URL,它只是留下了 {{ MEDIA_URL }} 的字样。

我错过了导入还是什么?管理平面页面的 default.html 扩展了我常用的模板,所以我看不出这会失败的原因,除非我不明白平面页面可以访问哪些内容?

【问题讨论】:

  • @AamirAdnan 这个问题与您标记为重复的内容无关..
  • @karthikr 怎么样? MEDIA_URL 和其他模板标签或上下文有什么区别?
  • @AamirAdnan 问题是,如何在平面页面中启用MEDIA_URL,而不是如何让平面页面接受模板标签。有很多方法可以做到这一点

标签: python html django django-templates django-flatpages


【解决方案1】:

您可以通过模板标签在平面页面中访问MEDIA_URLLook at this snippet 它会搜索 {{ MEDIA_URL }} 并将其替换为您在设置中找到的内容。

from django import template
from django.conf import settings
from django.template.defaultfilters import stringfilter

register = template.Library()

@register.filter
@stringfilter
def media_url(value):
    """Searches for {{ MEDIA_URL }} and replaces it with the MEDIA_URL from settings.py"""
    return value.replace('{{ MEDIA_URL }}', settings.MEDIA_URL)
media_url.is_safe = True

及用法:

{% load media_url %}
{{ flatpage.content|media_url }}

要进行设置,请将上述代码放入 templatetags 目录中的 media_url.py 文件中,然后将过滤器添加到您的平面模板中,如下所示

【讨论】:

  • 对于需要解决的问题,这是一个完美、简单的解决方案。非常感谢 karthikr!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-20
  • 2010-10-24
  • 2012-08-05
  • 2011-04-03
相关资源
最近更新 更多