我试图找到使用 django 的模板上下文加载器显示图像的最有效方法。我的应用程序中有一个静态目录,其中包含图像“victoryDance.gif”和项目级别的空静态根目录(带有settings.py
)。urls.py
假设我和settings.py
文件中的路径是正确的。什么是最好的景色?
from django.shortcuts import HttpResponse
from django.conf import settings
from django.template import RequestContext, Template, Context
def image1(request): # good because only the required context is rendered
html = Template('<img src="{{ STATIC_URL }}victoryDance.gif" alt="Hi!" />')
ctx = { 'STATIC_URL':settings.STATIC_URL}
return HttpResponse(html.render(Context(ctx)))
def image2(request): # good because you don't have to explicitly define STATIC_URL
html = Template('<img src="{{ STATIC_URL }}victoryDance.gif" alt="Hi!" />')
return HttpResponse(html.render(RequestContext(request)))
def image3(request): # This allows you to load STATIC_URL selectively from the template end
html = Template('{% load static %}<img src="{% static "victoryDance.gif" %}" />')
return HttpResponse(html.render(Context(request)))
def image4(request): # same pros as image3
html = Template('{% load static %} <img src="{% get_static_prefix %}victoryDance.gif" %}" />')
return HttpResponse(html.render(Context(request)))
def image5(request):
html = Template('{% load static %} {% get_static_prefix as STATIC_PREFIX %} <img src="{{ STATIC_PREFIX }}victoryDance.gif" alt="Hi!" />')
return HttpResponse(html.render(Context(request)))
感谢您的回答这些观点都有效!