티스토리 뷰

study/Django

Template 기본 구조

xoxowo 2023. 5. 11. 23:58

Django로 미니 프로젝트를 만들면서 MVC이 아닌 MVT 패턴을 활용하여 View에서 만든 로직을 Template을 활용해서 화면을 그려보고있는데, 개인적으로 어려웠던 (?) 부분을 정리해본다.

 

 

Template 폴더 구조 및 settings.py에 위치지정

 

프로젝트 manage.py 파일이 있는 경로에 templates 폴더와 static 폴더를 나눌수도 있고,

templates 폴더 내부에 static 폴더를 넣을 수도 있다.

또 static 폴더에는 css, js, img 등 따로 폴더를 나눠 정리할 수도 있다.

※ settings.py에 templates과 static 폴더 위치를 지정 해야한다. 💦

 

→  구조 예시

 

프로젝트 settings.py에 templates과 static 폴더 위치를 지정해준다.

폴더명\hyj\settings.py

# hyj/settings.py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [], # []를 [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',
            ],
        },
    },
]

# STATIC_URL 경로를 추가
STATIC_URL = '/static/'

# STATICFILES_DIRS 루트를 아래와 같이 코드 추가
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]

# BASE_DIR 는 파일이 위치한 폴더가 위치한 폴더, 즉 프로젝트 폴더를 의미한다.

 

 

 

Template 상속

공통으로 가지는 html화면 구조를 가진 템플릿을 기본(base.html)템플릿으로 만들고, 이를 상속받아 사용한다.

(기본적인 뼈대를 만든다고 생각하면 된다.)

 

※ html에 Django template 문법이 사용된다.

 

이전에 static 폴더에 넣은 css, js 파일을 사용할땐, {% load static %} 으로 settings.py에 작성한 static 파일들을 가져온다.

 {% load static %} 선언 시 base.html 맨 윗줄에 선언한다.

 

그리고 template 문법으로 href="{% static 'style.css' %}" css, js, 등등 경로를 지정해준다.

  경로에 따라 href="{% static 'style.css' %}"  'style.css' ← ' ' 안의 경로가 달라질 수 있다.

ex)   <link rel="stylesheet" type="text/css"  href="{% static 'css/style.css' %}">

 

그리고 <body>  태그 내부에 있는 {% block content %} {% endblock %} 태그에 이제 다른 템플릿에서 작성한 코드들이 들어간다.

 

template/base.html

{% load static %}
<!doctype html>
<html lang="ko">
<head>
    
    <!-- Required meta tags -->
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" type="text/css" href="{% static 'bootstrap.min4.css' %}">
    <!-- style CSS -->
    <link rel="stylesheet" type="text/css"  href="{% static 'style.css' %}">

    <title>🙋 HYJ ✨</title>
</head>
<body>

{% block content %}
{% endblock %}

</body>
</html>

 

base.html을 상속받은 게시판 메인 페이지 html 코드를 보면 <html>태그가 사용되지 않았는데,

서버 구동 후 메인 화면(main.html)의 코드를 보면 base.html에 작성한 코드들이 보이는 것을 알 수있다. 

 

 main.html는 {% extends 'base.html' %} 문법으로 base.html을 상속받았기 때문

 

 

main.html의  body를 살펴보면 main.html의 {% block content %} {% endblock %} 태그 내부에 작성한 코드들이 들어가있다.

 

 

 template/board/main.html

{% extends 'base.html' %}
{% block content %}
<div class="main">
    
    <div class="head-top">
        <div>
            <h1>공지 게시판</h1>
        </div>
    </div>

    <div class="board-main">
        <div class="new-button">
            <button class ="btn btn-primary btn-block" onclick="location.href='board/write'" >글쓰기</button>
        </div>

        <div class="table-main">
            <table class="table table-light">
                <thead class="thead-light">
                    <tr>
                        <th>번호</th>
                        <th>제목</th>
                        <th>본문</th>
                        <th>작성일</th>
                    </tr>
                </thead>
                <tbody class="text-dark">
                    {% if board_list %}
                    {% for board in board_list %}
                    <tr  class="text-center">
                        <th>{{ board.id }}</th>
                        <td style="cursor:pointer;" onclick="location.href='board/post/{{ board.id }}'">{{ board.title }}</td>
                        <td style="cursor:pointer; text-align: left;" onclick="location.href='board/post/{{ board.id }}'">{{ board.content|truncatechars:55 }}</td>
                        <td>{{ board.created_at|date:"Y-m-d"}}</td>
                    </tr>
                    {% endfor %}
                    {% else %}
                    <tr class="text-center">
                        <td colspan="5">
                            작성된 게시글이 없습니다.
                        </td>
                    </tr>
                    {% endif %}
                    
                </tbody>    
            </table>
        </div>

    </div>
</div>
{% endblock %}

 

 

'study > Django' 카테고리의 다른 글

authenticate() 함수  (0) 2023.05.29
Template - 검색 결과 내 페이지네이션  (0) 2023.05.22
Django - AWS S3 파일 업로드  (0) 2023.04.14
환경 변수 설정 (django-environ)  (0) 2023.04.13
Unit Test 작성  (0) 2023.03.02
댓글