Django template context processor
Django 에서 template 을 사용할 때 context 를 template 으로 넘겨서 template 에 값을 전달한다. 이 context 에 값을 추가하는 방법을 알아보자.직접 coding
아래처럼 TemplateView 를 상속받아서 context 에 직접 추가해 줄 수 있다. 하지만 아무래도 이 방법은 번거롭다.# coding=utf-8
from django.template.context_processors import csrf
from django.views.generic import TemplateView
from django.conf import settings
__author__ = 'namh'
class TemplateViewWithCsrf(TemplateView):
"""
This set the csrf which could be called by the Django template
"""
def get(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs)
context.update(csrf(request))
context.update({u"site_name": settings.SITE_NAME})
return self.render_to_response(context)
TEMPLATES.context_processors 를 이용
손쉽게 context_processor 를 이용할 수 있다.
- 자신만의 context_processors 를 만들고(참고: Writing your own context processors)
- settings.py 에서 TEMPLATES.context_processors 를 세팅하는 곳에 추가하면 된다.
//context_processors.py
# coding=utf-8
from django.conf import settings
def myproject_context(request):
"""
Adds static-related context variables to the context.
"""
return {
'MYCONTEXT': settings.MYCONTEXT
}
TEMPLATES = [{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [normpath(join(SITE_ROOT, 'templates'))],
'OPTIONS': {
'debug': DEBUG,
# see : https://docs.djangoproject.com/en/1.8/ref/templates/upgrading/
'context_processors': [
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.request',
# context of mine
'testproject.context_processors.myproject_context',
],
'loaders': [
# ('django.template.loaders.cached.Loader', [
# 'django.template.loaders.filesystem.Loader',
# 'django.template.loaders.app_directories.Loader',
# ]),
('pyjade.ext.django.Loader',(
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)),
],
'builtins': ['pyjade.ext.django.templatetags'],
},
}]
댓글 없음:
댓글 쓰기