URL Building and Templating with Jinja in Your Flask Application
Jinja
파이썬용으로 구축된 템플레이팅 언어
블로그의 일반적 레이아웃, 스타일링, 구조를 만들고 특정 페이지를 로딩할 때마다
제목이나 소제목, 본문과 같은 콘텐츠를 동적 콘텐츠로 교체
Jinja를 활용하여 동적 HTML 페이지 제작하기
Jinja 템플레이팅과 API 결합하기
Jinja에서의 멀티라인 구문
플라스크를 활용하여 URL 구축하기
블로그 캡스톤 프로젝트 - 템플레이팅
main.py
from flask import Flask, render_template
from post import Post
import requests
posts = requests.get("https://api.npoint.io/c790b4d5cab58020d391").json()
post_objects = []
for post in posts:
post_obj = Post(post["id"], post["title"], post["subtitle"], post["body"])
post_objects.append(post_obj)
app = Flask(__name__)
@app.route('/')
def get_all_posts():
return render_template("index.html", all_posts=post_objects)
@app.route("/post/<int:index>")
def show_post(index):
requested_post = None
for blog_post in post_objects:
if blog_post.id == index:
requested_post = blog_post
return render_template("post.html", post=requested_post)
if __name__ == "__main__":
app.run(debug=True)
post.py
class Post:
def __init__(self, post_id, title, subtitle, body):
self.id = post_id
self.title = title
self.subtitle = subtitle
self.body = body
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link href="https://fonts.googleapis.com/css2?family=Raleway" rel="stylesheet">
<link rel="stylesheet" href="../static/css/styles.css">
</head>
<body>
<div class="wrapper">
<div class="top">
<div class="title"><h1>My Blog</h1></div>
</div>
</div>
</body>
<footer>
<p>Made with ♥️ </p>
</footer>
</html>
post.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link href="https://fonts.googleapis.com/css2?family=Raleway" rel="stylesheet">
<link rel="stylesheet" href="../static/css/styles.css">
</head>
<body>
<div class="wrapper">
<div class="top">
<div class="title"><h1>My Blog</h1></div>
</div>
<div class="content">
<div class="card">
<h1> </h1>
<h2> </h2>
<p> </p>
</div>
</div>
</div>
</body>
<footer>
<p>Made with ♥️</p>
</footer>
</html>