본문 바로가기
BE/Flask

flask template engine, Jinja2: 변수, if문, 필터 요약 정리

by 벼락코드 2025. 1. 29.

flask template engine, Jinja2: 기본 문법

node.js의 ejs처럼 flask에서 사용하는 템플릿 엔진으로는 Jinja2가 있다.

ejs와 문법이 비슷해서 사용하기 쉬운 것 같다.

 

 

0. directory setting

template으로 사용되는 .html 파일들은 templates directory에 있어야 한다.

 

1. 변수와 제어문

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <h1>hello, {{ name }}!</h1>

    <!-- 변수와 제어문(if, else, endif문) -->
    {% if name %}
    <h1>Hello, --{{name}}--</h1>
    {% else %}
    <h1>Hello, no name !</h1>
    {% endif %}
  </body>
</html>

 

 

2. 필터

  • 변수의 값을 출력하기 전, 변형하는 단계
  • 예시
    • 사용자가 입력한 문자열을 대문자로 변환
    • 날짜 형식 변환
    • 사용자 정의 필터 추가
<h1>📌필터 기능</h1>
<p>{{ user_name|capitalize }}</p>  // 앞글자만 대문자화 됨
<p>{{ story|truncate(100) }}</p>
<p>{{ timestamp|date("Y-m-d H:i") }}</p>

 

from jinja2 import Template

# safe 필터 사용 예시
template = Template('{{ my_html|safe }}')
my_html = '<p>This is <strong>bold</strong> text.</p>'
output = template.render(my_html=my_html)
print(output)
  • 필터 옵션 종류
    • safe: HTML 태그를 이스케이핑하지 않음
      • Jinja2는 자동 이스케이프 기능 제공
      • html 특수문자( <, >, &, " )를 이스케이프 하여 XSS공격을 방지하기 위함임
      • 그러나 때로 html 코드를 템플릿에 직접 삽입해야하는 경우, safe 필터를 사용
    • capitalize: string의 맨 앞글자를 대문자로 변환
    • upper: string 모두 대문자로 변환
    • lower
    • title: string의 각 단어 첫 글자를 대문자로 변환
    • trim: string의 앞뒤 공백 제거
    • striptages: string에서 HTML 태그 제거
    • truncate(n): n만큼 string길이 조정
    • date("Y-m-d H:i"): datetime 객체를 문자열로 포멧

 

3. 반복문 ( {% for ~in %} ... {% endfor %}

# 기본 반복문
<ul>
  {% for item in items %}
    <li>{{ item }}</li>
  {% endfor %}
</ul>

# 인덱스 사용
<ul>
  {% for item in items %}
    <li>{{ loop.index }}. {{ item }}</li>
  {% endfor %}
</ul>

# 짝수/홀수 구분
# loop.index is even: 현재 반복 횟수가 짝수인지 확인
<ul>
  {% for item in items %}
    <li class="{% if loop.index is even %}even{% else %}odd{% endif %}">{{ item }}</li>
  {% endfor %}
</ul>

# 반복문 중간에 조건 추가
# 세 번째 요소에서 class="highlight"추가
<ul>
  {% for item in items %}
    <li>{{ item }}</li>
    {% if loop.index == 2 %}
      <li class="highlight">중간 요소</li>
    {% endif %}
  {% endfor %}
</ul>

# 빈 리스트 처리: else문 처리
<ul>
  {% for item in items %}
    <li>{{ item }}</li>
  {% else %}
    <li>항목이 없습니다.</li>
  {% endfor %}
</ul>

# 중첩 반복문
<table>
  {% for row in rows %}
    <tr>
      {% for cell in row %}
        <td>{{ cell }}</td>
      {% endfor %}
    </tr>
  {% endfor %}
</table>
  • 반복문 변수
    • loop.index: 현재 반복 횟수(1부터 시작)
    • loop.index0: 현재 반복 횟수(0부터 시작)
    • loop.first: 첫 번째 반복인지 여부
    • loop.last: 마지막 반복인지 여부
    • loop.even: 짝수 번째 반복인지 여부
    • loop.odd
    • loop.length: 전체 반복 횟수