上下文渲染器RequestContext
阿新 • • 發佈:2017-09-08
hit pre bit options family mon join lnl path
在render_to_response中加RequestContext會將settings中設置的context_processors返回值收集起來傳到模板
return render_to_response(‘index.html‘, {...}, context_instance=RequestContext(request))
settings.py
TEMPLATES = [ { ‘BACKEND‘: ‘django.template.backends.django.DjangoTemplates‘, ‘DIRS‘: [os.path.join(BASE_DIR, ‘templates‘)] , ‘APP_DIRS‘: True, ‘OPTIONS‘: { ‘context_processors‘: [ ‘django.template.context_processors.debug‘, ‘django.template.context_processors.request‘, ‘django.contrib.auth.context_processors.auth‘,‘django.contrib.messages.context_processors.messages‘, ‘BookStore.views.global_settings‘, ‘django.template.context_processors.media‘, ‘BookStore.context_processor.ip_address‘, ], }, },
可以手動寫個上下文渲染器(以下摘自自強學堂):新建context_processor.py
添加以下內容
def ip_address(request): return {‘ip_address‘: request.META[‘REMOTE_ADDR‘]}
settings.py中加入對應路徑,如上面的settings.py加入了‘BookStore.context_processor.ip_address‘
在模板中就可以使用
{{ ip_address }}
https://lincolnloop.com/blog/2008/may/10/getting-requestcontext-your-templates/
這裏有如何向render_to_response添加RequestContext的方法。
有個@render_to感覺非常經典,代碼如下
def render_to(template_name): def renderer(func): def wrapper(request, *args, **kw): output = func(request, *args, **kw) if not isinstance(output, dict): return output return render_to_response(request, template_name, output) return wrapper return renderer @render_to(‘my_template.html‘) def my_view(request): # View code here... return some_dict
上下文渲染器RequestContext