What I Learned

TIL_20220926_Django template language

오베르 2022. 9. 26. 22:27

장고 템플릿 언어 (The Django template language)

- Syntax

 

변수 (Variables)

- 변수는 컨텍스트(context)로부터 값을 출력, 

 · 컨텍스트(context)는keys 를 values 로 맵핑하는 dic-like object

 · 컨텍스트(context)는 템플릿에서 쓰이는 변수명과 Python 객체를 연결하는 사전형 값

- 변수는 {{  }} 로 둘러 쌓여있다.

My first name is {{ first_name }}. My last name is {{ last_name }}.

- {'first_name': 'John', 'last_name': 'Doe'}, 의 컨텍스트와 이 템플릿은 아래처럼 렌더된다.

My first name is John. My last name is Doe.

Dictionary lookup, attribute lookup and list-index lookup은 아래와 같이 닷 으로 실행된다.

{{ my_dict.key }}
{{ my_object.attribute }}
{{ my_list.0 }}

If a variable resolves to a callable, the template system will call it with no arguments and use its result instead of the callable.

 


태그 (Tag)

 

태그는 렌더링 프로세스에서 arbitrary 한 logic 을 제공한다.

더보기

arbitrary : 임의의

- 대상이 되는 것들 중에서 무엇을 선택해도 성능, 비용 등에 영향을 주지 않는 경우에 사용
출처: https://gazelle-and-cs.tistory.com/30 [Gazelle and Computer Science:티스토리]

This definition is deliberately vague. 

For example, a tag can output content, serve as a control structure 

e.g. an “if” statement or a “for” loop, grab content from a database, or even enable access to other template tags.

 

 

태그들은 {% %} 로 둘러 쌓여있다.

{% csrf_token %}

대부분의 태그들은 인자를 허용한다.

{% cycle 'odd' 'even' %}

어떤 태그들은 처음과 끝을 요구한다.

{% if user.is_authenticated %}Hello, {{ user.username }}.{% endif %}
 

필터 (Filter)

 

- 필터들은 변수와 태그의 인자 값을 변형한다.

아래와 같이 표기

{{ django|title }}

{'django': 'the web framework for perfectionists with deadlines'}, 와 같은 컨텍스트를 템플릿은 아래처럼 렌더링 한다.

The Web Framework For Perfectionists With Deadlines

어떤 필터들은 인자를 가진다.

{{ my_date|date:"Y-m-d" }}

코멘트 (Comment)

- 코멘트는 아래와 같이 표기

{# this won't be rendered #}

- {% comment %} tag 는 여러줄의 코멘트를 제공한다.

 

참조 :

템플릿 | Django 문서 | Django (djangoproject.com)

6-1. [DTL] django template language