繁体   English   中英

如何在Django中“有条件地”提供静态文件

[英]How to serve static files 'conditionally' in Django

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

在此处输入图片说明

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

任何帮助将不胜感激。

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

首先做一个合适的过滤器:

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}}">

仅当您的每个模板都继承自使用这些通用路径的某个基本模板时,这才真正有用,但是每个模板都需要一个不同的图像或某种外观来满足您的需求。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM