# Django Template

```python
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',
            ],
        },
    },
]
```

`project/settings.py`에 **TEMPLATES** 관련 설정을 하고 있는 것을 볼 수 있다. 여기서는 어떻게 tmeplate을 불러오고 렌더링 할 것인지를 설정할 수 있다.

`'APP_DIRS': True` 는 **INSTALLED\_APPS** 디렉토리의 **templates** 하위 디렉토리를 탐색한다.

## Template 파일 생성하기

템플릿을 생성할 app 디렉토리 하위에 **templates** 디렉토리를 생성한다. templates 디렉토리 하위에 polls 디렉토리 내부에 `index.html` 파일을 생성해준다.

```
polls
├── __init__.py
├── admin.py
├── apps.py
├── migrations
│   ├── 0001_initial.py
│   ├── __init__.py
├── models.py
├── templates
│   └── polls
│       └── index.html
├── tests.py
├── urls.py
└── views.py
```

> `polls/templates/polls/index.html` 과 같은 형태가 된다. 여기서 왜 templates 디렉토리 하위에 polls 디렉토리를 생성해준걸까?
>
> Django에서는 이름이 일치하는 첫번째 template을 선택한다. 만약 동일한 template이 다른 어플리케이션에 있을 경우에 이 둘의 차이를 구분하지 못한다. 가장 정확한 template을 지정하기 위해서 가장 편리한 방법은 *이름공간*으로 구분짓는 것이다.

```markup
<!-- polls/index.html -->
{% if last_question_list %}
    <ul>
        {% for question in last_question_list %}
            <li><a href="/polls/{{question.id}}/">{{ question.question_text}}</a></li>
        {% endfor %}
    </ul>
{% else %}
   <p>No polls are avaliable.</p>
{% endif %}
```

## Template 언어

HTML(정적)에 파이썬 코드(동적)를 바로 넣을 수 없다. **template tag`{}`**&#xB294; 파이썬을 HTML으로 바꾸어 빠르고 쉽게 동적인 웹사이트를 만들 수 있다.

> ruby에서는 `html.erb`

### `{{변수}}`

context로 전달된 변수를 템플릿에서 값을 출력하려면 다음과 같이 중괄호 안에 변수이름을 넣어서 표시할 수 있다.

```markup
<h1>{{ title }}</h1>
<p>{{ context }}</p>
```

### `{%%}` 템플릿 태그

\`

\` 태그 안에는 python의 for문, if문과 같이 탬플릿의 로직을 제어한다.

```markup
{% if count > 0 %}
    Data Count = {{ count }}
{% else %}
    No Data
{% endif %}

{% for item in dataList %}
  <li>{{ item.name }}</li>
{% endfor %}

{% csrf_token %}
```

* [내장 태그 레퍼런스](https://docs.djangoproject.com/ko/2.1/ref/templates/builtins/#ref-templates-builtins-tags)

### `{{ | }}` 필터

템플릿 필터는 변수의 값을 특정한 포맷으로 변형하는 기능을 한다. 이때 `|` 파이프를 사용해 필터를 적용한다.

예를 들어, 날짜를 특정 날짜 포맷으로 변경하거나, 문자열을 대,소문자로 변경하는 기능을 할 수 있다.

```markup
<!--날짜 포맷 지정-->
{{ createDate|date:"Y-m-d" }}

<!--소문자 변경-->
{{ lastName|lower }}

<!-- 라인 변경 -->
{{ post.text|linebreaksbr }}
```

[내장 필터 레퍼런스](https://docs.djangoproject.com/ko/2.1/ref/templates/builtins/#ref-templates-builtins-filters) 에서 전체 목록을 볼 수 있으며, 템플릿 필터를 직접 만들 수 있다.

### \`\` 주석 <a href="#undefined" id="undefined"></a>

템필릿에서 주석구문은 `{# #}`이다.

```markup
{# 주석, 코드에 대한 설명 #}
```

### HTML Escape

HTML 내용중에 `<,>,',",&` 과 같은 문자들이 있으면 그 문자에 상응하는 HTML Entity로 변환해주어야한다.

템플릿에서 이러한 작업을 자동으로 처리해주기 위해서 \`

`템플릿 태그나`escape\` 템플릿 필터를 사용한다.

```markup
# autoescape 태그
{% autoescape on %}     
    {{ content }}
{% endautoescape %}

# escape 필터
{{ content|escape }}
```

## 참조

* 공식 레퍼런스
  * [templates](https://docs.djangoproject.com/ko/2.1/topics/templates/)
  * [Built-in template tags and filters](https://docs.djangoproject.com/en/2.1/ref/templates/builtins/#filter)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dahye-jeong.gitbook.io/til/django/basic/2019-03-09-template.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
