我有一些背景资料.我希望能够从模板中访问,但我不知道该怎么做.我已经试过了
{{CONSTANT_NAME}}
但这似乎不起作用.这可能吗?
我有一些背景资料.我希望能够从模板中访问,但我不知道该怎么做.我已经试过了
{{CONSTANT_NAME}}
但这似乎不起作用.这可能吗?
如果您使用Django内置的通用视图或在render_to_response
快捷方式函数中传入上下文实例关键字参数,则Django提供对模板的某些常用设置常量(如settings.MEDIA_URL
)和一些语言设置的访问.下面是每种情况的示例:
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.views.generic.simple import direct_to_template
def my_generic_view(request, template='my_template.html'):
return direct_to_template(request, template)
def more_custom_view(request, template='my_template.html'):
return render_to_response(template, {}, context_instance=RequestContext(request))
这两个视图都有几个经常使用的设置,如settings.MEDIA_URL
可用于模板,如{{ MEDIA_URL }}
等.
如果您希望访问设置中的其他常量,则只需解压缩所需的常量并将其添加到视图函数中使用的上下文字典中,如下所示:
from django.conf import settings
from django.shortcuts import render_to_response
def my_view_function(request, template='my_template.html'):
context = {'favorite_color': settings.FAVORITE_COLOR}
return render_to_response(template, context)
现在,您可以将模板上的settings.FAVORITE_COLOR
作为{{ favorite_color }}
进行访问.