본문 바로가기
App Programming/Django

[Django] 템플릿 (Template)

by goatlab 2023. 6. 22.
728x90
반응형
SMALL

템플릿 (Template)

 

 

Django 템플릿은 Django 템플릿 언어를 사용하여 마크업된 텍스트 문서 또는 Python 문자열이다. 일부 구문은 템플릿 엔진에서 인식하고 해석한다. 주요 항목은 변수와 태그이다. 템플릿은 컨텍스트로 렌더링된다. 렌더링은 컨텍스트에서 조회되는 값으로 변수를 대체하고 태그를 실행한다. 나머지는 그대로 출력된다.

 

프로젝트 템플릿 디렉토리는 TEMPLATES 설정의 DIRS 항목에 지정된 디렉토리이다. 앱 템플릿 디렉토리는 각 어플리케이션 디렉토리마다 존재하는 templates/ 디렉토리를 말한다. 프로젝트 디렉토리에는 base.html 등 전체 프로젝트의 룩앤필에 관련된 파일들을 모아두고 각 앱에서 사용하는 템플릿 파일들은 앱 템플릿 디렉토리에 위치시킨다. 일반적인 경우 템플릿 디렉토리는 다음과 같다.

 

  • 프로젝트 베이스 (루트) 디렉토리 : /project/
  • 프로젝트 디렉토리 : /project/project/
  • 프로젝트 템플릿 디렉토리 : /project/templates/
  • 앱 템플릿 디렉토리 : /project/app/templates/

 

장고는 별도의 변경이 없다면 프로젝트 템플릿 디렉토리를 먼저 검색하고 그 다음 앱 템플릿 디렉토리를 검색한다. 앱 템플릿 디렉토리가 여러개 존재한다면 INSTALED_APPS 설정 항목에 등록된 순서대로 검색한다.

 

구문 (Syntax)

 

# 템플릿 엔진 사용법

{{ 변수명 }}

{% if 조건문 %}
{% else %}
{% endif %}

{% for x in iter %}
{% endfor %}

 

투표 어플리케이션 만들기

 

polls/templates/polls 폴더에서 base, detail, index, results html을 생성한다.

 

<!-- base.html -->
<!doctype html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>
        {% block title %}My Site{% endblock %}
    </title>
</head>
<body>
    <div>
        {% block content %}{% endblock %}
    </div>
</body>
</html>
<!-- detail.html -->
<form action="{% url 'polls:vote' question.id %}" method="post">
    {% csrf_token %}
    <fieldset>
        <legend>
            <h1>{{question.question_text}}</h1>
        </legend>
        {% if error_message %}
        <p><strong>{{error_message}}</strong></p>
        {% endif %}
        {% for choice in question.choice_set.all %}
        <input type="radio" name="choice" id="choice{{forloop.counter}}" value="{{choice.id}}">
        <label for="choice{{forloop.counter}}">{{ choice.choice_text }}</label>
        <br>
        {% endfor %}
    </fieldset>
    <input type="submit" value="Vote">
</form>
<!-- index.html -->
{% extends "base.html" %}

{% block title %}My Title{% endblock %}

{% block content %}
<!--views.py > index > context > latest_question_list -->
{% if latest_question_list %}
<ul>
    {% for question in latest_question_list %}
    <li>
        <a href="/polls/{{question.id}}">{{ question.question_text|default:'질문이 없습니다.' }}</a>
    </li>
    {% endfor %}
</ul>
{% else %}
<p>투표가 없습니다.</p>
{% endif %}
{% endblock %}
<!-- results.html -->
<h1>{{question.question_text}}</h1>

<ul>
    {% for choice in question.choice_set.all %}
    <li>
        {{ choice.choice_text }} - {{ choice.votes }} vote{{ choice.votes|pluralize }}
    </li>
    {% endfor %}
</ul>

<a href="{% url 'polls:detail' question.id %}">Vote again?</a>

 

https://docs.djangoproject.com/en/4.2/topics/templates/

 

Django

The web framework for perfectionists with deadlines.

docs.djangoproject.com

728x90
반응형
LIST

'App Programming > Django' 카테고리의 다른 글

[Django] 템플릿 시스템 (1)  (0) 2023.06.26
[Django] 셸로 데이터 다루기  (0) 2023.06.23
[Django] 뷰 (View)  (0) 2023.06.22
[Django] URL  (0) 2023.06.20
[Django] 모델 (Model)  (0) 2023.06.20