- Django의 View에서 Html을 연결하기 위한 Template 엔진 관련 설정법을 정리합니다.
1. Template 이란?
- 웹서버프레임워크에서는 html을 동적으로 생성하기 위해 Template을 사용합니다.
- Node.js의 ejs 템플릿 엔진 예시 입니다.
<% %>
기호 안에for
문이 보입니다.- 이렇게 동적으로 html을 생성하기 위한 구문들을 템플릿 엔진이라고 합니다.
- view 함수에서 동적으로 생성된 html을 리턴해주기 위해서는 template엔진을 이용하며 이를 이용하기 위해서는 설정이 필요합니다.
<html>
<head>
<title><%= title %></title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<h1>Loop it!</h1>
<ul>
<% for(var i=0; i<length; i++){ %>
<li>
<%= "LOOP" + i %>
</li>
<% } %>
</ul>
</body>
</html>
- Django의 Template 예시 입니다.
{% extends 'layout/main_layout.html' %}
{% load staticfiles %}
{% block content %}
<h1>Blog List</h1>
<ul>
{% for blog in blog_list %}
<li>
<a href="{{ blog.get_blog_url }}">{{ blog.title }}</a>
</li>
{% endfor %}
</ul>
{% endblock %}
2. Template 설정
- 기본적으로 Django는 기본값으로 Template 설정이 되어 있습니다.
프로젝트명/settings.py
에 아래와 같은 항목이 있습니다.
... 생략
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
],
},
},
]
... 생략
- 아래의 항목은
DjangoTemplates
django 기본 템플릿을 이용함을 의미합니다. django.template.backends.jinja2.Jinja2
모듈도 사용가능하나jinja2
모듈을 설치해야만 합니다.
...생략
'BACKEND': 'django.template.backends.django.DjangoTemplates'
...생략
- 아래의 항목은 각각의 앱 디렉토리 검색 여부를 결정합니다.
True
값을 입력할 경우 앱디렉토리내에templates
디렉토리를 검사합니다.
... 생략
'APP_DIRS': True,
... 생략
- 아래의 항목은
'APP_DIRS': True
옵션을 통해 자동적 template을 찾아주지만, 추가로 다른 디렉토리를 사용할 경우 아래의 항목을 이용합니다. - 템플릿을 App디렉토리가 아닌 프로젝트 디렉토리 바로 아래에 이용하고자 한다면 아래와 같이 입력합니다. 디렉토리 명은 변경할 수 있습니다.
- Django는
'DIRS':[]
항목을 먼저 탐색 한 후, APP의 디렉토리를 탐색하여 지정된 Template을 찾습니다.
'DIRS': [
'templates',
],
- 아래
OPTIONS
항목은 템플릿 엔진 고유의 설정이 입력됩니다. - 대부분 기본값으로 사용하리라 생각되기에 링크로 대체합니다.