본문 바로가기

Flask

[Flask] Jinja2 이용하여 for loop 사용하기

파이썬 앱파일에 테스트용 더미 데이터를 만들어보자

딕셔너리 형식의 리스트 파일

posts = [
    {
        'author' : '업철이',
        'title' : '첫번째 블로그 포스트',
        'content' : '첫번째 블로그 포스트 내용',
        'date_posted' : 'Jan 16, 2023'
    },
    {
        'author' : '제리',
        'title' : '두번째 블로그 포스트',
        'content' : '두번째 블로그 포스트 내용',
        'date_posted' : 'Jan 18, 2023'  
    }
        ]

 

home.html에 posts 내용 불러들이기

posts는 render_template function

def hello():
    return render_template('home.html', posts = posts)

 

home.html의 body 부분에 jinja2 템플릿 문법에 따라 작성

*** for loop 사용시 for loop 끝나는 부분을 명시해야 함 ***

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    {% for post in posts %}
        <h1>{{ post.title }}</h1>
        <p>By {{ post.author}} on {{ post.date_posted }}</p>
        <p>{{ post.content }}</p>
    {% endfor %}
</body>
</html>
 
 
 

웹페이지 화면

for loop 적용되서 포스트 두 개 모두 작성됨

 

페이지 소스 확인

for loop 족용되서 포스트 두 개 모두 작성됨