利用Flask製作一個Blog

Import flask

通過route連接index.html,建立基本的Hone page

在使用Flask時要將html放到templates資料夾中,css與圖片等放到static資料夾。

#main.py
from flask import Flask, render_template, request
app = Flask(__name__)

@app.route("/")
def home_page():
    return render_template("index.html")

if __name__ == "__main__":
    app.run(debug=True)

這邊使用的是現成的Template,可以將每一個html中的 header 、 footer 獨立出來再導入各個分頁中方便管理。

<!-- header.html -->
<head>
...
</head>
<!-- Navigation -->
<body>
...
</body>

導入其他分頁中

<!-- Head & Navigation -->
{% include "header.html" %}
...
...
<!-- Footer -->
{% include "footer.html" %}

可以在render_template中導入自訂變數

#main.py
@app.route("/")
def get_all_posts():
    return render_template("index.html", all_posts=posts) #posts是dictionary

再從html中使用Jinja的dot notation取得dictionary的資料

(Jinja is already bundled in Flask)

<!--index.html-->
{% for post in all_posts %}            <!-- jinja -->
	  <div class="post-preview">
	      <a href="{{ url_for('get_post',index=post.id) }}">
	      <h2 class="post-title">
	          {{post.title}}             <!-- Dot notation -->
	      </h2>
	      <h3 class="post-subtitle">
	          {{post.subtitle}}
	      </h3>
	      </a>
	      <p class="post-meta">Posted by
	          <a href="#">{{post.author}}</a>
	          on {{post.date}}</p>
	  </div>
	  <!-- Divider-->
	  <hr class="my-4" />
{% endfor %}

首頁完成後再創建一個route連接各個文章

@app.route("/<int:index>")
def get_post(index): #從index.html中點選文章時會回傳post.id到這裡
    requested_post = None
    for blog_post in posts:
        if blog_post["id"] == index:  #配對之後把文章的內容放到requested_post中
            requested_post = blog_post
    return render_template("post.html", post=requested_post)

讓對應的文章內容顯示在post.html

....
<div class="col-md-10 col-lg-8 col-xl-7">
    <div class="post-heading">
        <h1>{{post.title}}</h1>
        <h2 class="subheading">{{post.subtitle}}</h2>
        <span class="meta">
            Posted by
            <a href="#!">{{post.author}}</a>
            on {{post.date}}
        </span>
    </div>
</div>
...
<div class="container px-4 px-lg-5">
    <div class="row gx-4 gx-lg-5 justify-content-center">
        <div class="col-md-10 col-lg-8 col-xl-7">
            <p>{{post.body}}</p> 
        </div>
    </div>
</div>

HTML Forms in Flask