본문 바로가기
작업

Django Template

by 저녁추천좀 2023. 6. 12.

 

https://docs.djangoproject.com/en/4.2/topics/templates/ 의 내용

 

Django 는 동적으로 HTML을 생성함. 특정한 syntax를 사용해서 HTML의 정적인 부분을 동적으로 삽입할 수 있다. 

간단한 예제는 https://docs.djangoproject.com/en/4.2/intro/tutorial03/ 를 보라. 

 

다양한 template enginege 을 사용가능하다. 장고는 DTL이라는 내장 엔진이 있지만 유명한 대체재는 JinJa2이다. 

: fastapi의 Jinja2Template를 사용할 것임

 

...

 

Django template language 는 장고의 template 시스템이다. 

자세한 내용을 보려면 https://docs.djangoproject.com/en/4.2/ref/templates/language/를 보라

 

The Django template language

Variables

 

context에서 dictionary like 매핑을 사용하여 불러온다.

{{ 와 }}로 표현한다.

다음과 같은 구문은

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

Context가  {'first_name': 'John', 'last_name': 'Doe'} 일 떄,

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

같은 출력을 낸다. 

 

dictionary look up음 다음처럼

 

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

만약에 변수가 callable이라면, template 시스템은 인자없이 호출한 출력을 반환할 것이다. 

 

 

Tags

렌더링 처리에 특정한 로직을 부여해줌

 

{% %} 으로 사용

 

인자가 필요하거나

 

{% cycle 'odd' 'even' %}

end 문이 필요할 수 있음

 

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

 

Filters

변수나 태그를 변환

{{ django|title }}

title 은 시작 문자를 대문자로 변환

The Web Framework For Perfectionists With Deadlines

인자를 요구할 수 도 있다.

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

Comments

Comments look like this:

{# this won't be rendered #}

A {% comment %} tag provides multi-line comments.