[英]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.