Django - templates 관리하기
base를 사용하여 templates를 관리하는 이유
- 페이지를 이동하더라도, 겹치는 상단 메뉴나, 하단 정보창이 존재
- 해당과 같이 진행하게 된다면, 반복해서 작성해야되고 비효율적이다.
- base를 활용하면, 새로 작성할 페이지의 기능에만 집중하여 효율적인 코드 작성 가능
base.html의 위치와 settings.py
- base.html은 보통 프로젝트의 root 디렉토리에 templates폴더를 새로 만들어 관리한다.
- base.html에서 사용하는 css파일, 이미지 등의 파일은 마찬가지로 root 디렉토리에 static폴더를 새로 만들어 관리한다.
- 하지만 django는 기본적으로 root에 위치한 templates와 static 폴더를 탐색하지 않는다.
- 따라서 settings.py에서 옵션을 수정해줘야 한다.
base.html 기본 구성
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="{% static 'style.css' %}" type="text/css"/>
{% block style %}
{% endblock %}
</head>
<body>
{% block content %}
{% endblock %}
</body>
</html>
- base에 작성된 코드를 제외하고
{% block style %} / {% block content %}
에 작성될 부분만 작성하면 된다.
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',
],
},
},
]
- settings.py에 옵션을 수정해준다.
- TEMPLATES에 대해 적힌 부분을 찾아 DIRS를 수정
- os.path.join(BASE_DIR, ‘templates’)를 기입한다.
base.html 활용
{% extends "base.html" %}
{% block static %}
<!--이 곳에 static에 해당하는 코드 (css파일 연결 등) 작성-->
{ % endblock % }
{% block content %}
<!--이 곳에 페이지의 내용 작성-->
{% endblock %}