如何有条件地提供静态文件'在Django

时间:2014-06-28 20:30:37

标签: django apache mod-wsgi

我有一个应用程序,其中包含在其单独的存储库中维护的模板。这是目录结构:

enter image description here

正如您所看到的,每个模板都有自己的一组静态文件。我的问题是如何使用适当的静态文件渲染每个模板?我愿意接受任何可以在生产中使用的可行解决方案。我使用apache2和mod_wsgi进行生产,如果需要,我也准备使用dj-static。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

您可以注册在所有静态文件路径上调用的过滤器,并将模板静态文件路径传递给您的上下文。

首先制作一个合适的过滤器:

from django.template import Library
from urlparse import urljoin
register = Library()
from django.conf import settings


@register.filter
def make_static(relative_url, template_dir):
    base = urljoin(settings.STATIC_URL, template_dir)
    return urljoin(base, relative_url)

现在,在渲染模板时,添加对模板静态文件所在位置的引用:

from django.template import Context
from django.template.loader import get_template

template = get_template('template1/index.html')
context = Context({'template_dir': 'template1/'})
template.render(context)

在您的实际模板中使用过滤器,如下所示:

<img src="{{'imgs/some_image.jpg'|make_static:template_dir}}">

如果您的每个模板都继承自使用这些通用路径的某个基本模板,但每个模板需要不同的图像或某些内容以便您按照自己喜欢的方式显示,这将非常有用。

相关问题