Django 의 기본 Template 엔진을 대신해서 최근 NodeJS 에서 많이 사용하는 Jade 템플릿 엔진을 사용할 수 있을까? 솔직히, Django 의 기본 템플릿 언어는 꽤 타이핑 해야 할 양도 많고, 그리 좋은지 모르겠다.
결론부터 말하자면, Django 에서는 PyJade 를 이용하여 Jade와 같은 문법으로 템플릿 파일을 만들 수 있다.
PyJade 는 *.jade 파일의 내용을 파이썬의 템플릿 언어(Django, Jinja2, Mako or Tornado) 형태로 변환해주는 역할을 수행함으로써 개발자로 하여금 좀 더 쉽게 템플릿 파일을 만들 수 있게 해준다.
PyJade 의 사용은 아래와 같은 절차대로만 수행하면 끝~!
설치
$ pip3 install pyjade
Template Loader 설정
Django 프로젝트 내 settings.py 파일 내 Template 설정 영역을 아래와 같이 수정한다. (Django 1.8 이상)
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': False,
'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'
],
'loaders': [
('pyjade.ext.django.Loader',(
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
))
],
},
},
]
jade 파일 생성
Django 어플리케이션 내 templates 디렉터리 내에 jade 파일을 생성한다.
!!! 5
html(lang="en")
head
title= pageTitle
script(type='text/javascript')
|if (foo) {
| bar()
|}
body
h1.title Jade - node template engine
#container
if youAreUsingJade
p You are amazing
else
p Get on it!
urlConf 설정
urls.py 파일에 url과 view를 매칭해준다.
from django.conf.urls import include, url
from polls import views
urlpatterns = [
url(r'^$', views.index, name = 'index'),
]
view 함수 설정
views.py 파일을 아래와 같이 코딩한다.
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from polls.models import Question, Choice
# Create your views here.
def index(request):
context = {'pageTitle': 'JADE 사용', 'youAreUsingJade': True}
return render(request, 'polls/index.jade', context)
페이지 확인
서버를 실행시키면 브라우저를 통해 아래와 같은 화면을 확인할 수 있다.
PyJade 적용 끝~
PyJade 로 생산성을 높여보자!!