# 前言
在大學和碩士期間主要都是接觸深度學習和電腦視覺的方面的研究,但最近慢慢發現,除了要會這些,許多公司也更重視如何把模型的結果接上後端的API或APP來做使用。但我對製作API或APP是完全沒有概念的,所以這是開始學習製作API和APP的第一天。
這是我的學習紀錄,所有範例都是跟著[Book_Python Flask實作記錄](https://hackmd.io/GVo6X6LoS3GNIW50LBJytw)的教學,並使用我自己的方法整理,以及加上自己的看法。
# 說明
網頁開發中,有許多html文件的架構是相同的,可能就是title不同,或是其他小地方。但若對每個小調整都建立一個新的html文件,會花費太多時間,也非常累人。所以此篇要學習透過jinja2的樣板繼承簡化重複性的網頁開發工作。
jinja2帶有樣板繼承的功能,可避免掉重複性的網頁開發工作。實際上會先建立一個基礎樣板(```base.html```)提供其他html文件繼承,完整語法結構可參考jinja2官方文件。
==jinja2表達式大致如下:==
```html=
{% block block_name %}
{% endblock block_name %}
```
- 建立基礎樣板```base.html```
```html=
<!DOCTYPE html>
<html lang="en">
<head>
{% block head %}
<meta charset="UTF_8">
<meta name="viewport" content="width=device-width, initial-scle=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>
{% block title %}{% endblock title %} -titleBlock
</title>
{% endblock head %}
</head>
<body>
<h1>Welcome to the test HTML</h1>
<h2>大家都要用的就不要用block處理</h2>
<h3>block的區塊是提供調整的部分</h3>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ur class="flash">
{% for message in messages %}
<li>{{message}}</li>
{% endfor %}
</ur>
{% endif %}
{% endwith %}
<div class="content">
{% block content %}
{% endblock content %}
</div>
</body>
</html>
```
第9行:建立一個```block```,命名為```title```
第27行:建立一個```block```,命名為```content```
上面的html文件中有兩個```block```,分別為```title```和```content```。這兩個```block```代表繼承此樣板的html文件可以修改的地方,其餘的部分皆透過繼承方式產生。
NOTE:對於繼承```base.html```的文件,在文件的開頭需透過```extends```來宣告
- 修改11_login.html來說明
```html=
{% extends "11_base.html" %}
{% block title %}Login{% endblock title%}
{% block content %}
<form method="post" action={{ url_for('login')}} >
<p>
<input type="text" name="username">
</p>
<p>
<input type="text" name="password">
</p>
<p>
<button type="submit">Submit</button>
</p>
</form>
{% endblock content %}
```
第1行:宣告繼承樣板```base.html```
第2行:利用```block title```設置```11_login.html```的```title```
第3行:利用```block content```設置```11_login.html```的內容
- 此範例的python如範例10的py檔
```python=
from flask import Flask, request, redirect, url_for, render_template, flash
# 固定格式
app = Flask(__name__)
# 登入畫面
@app.route('/loginurl', methods=['GET', "POST"])
def login():
if request.method == 'POST':
if check(request.form['username'], request.form['password']):
flash('Login Success')
return redirect(url_for('hello', username=request.form.get('username')))
return render_template('11_login.html')
def check(username, password):
if username == "admin" and password == "hello":
return True
else:
return False
# hello page畫面
@app.route('/hello/<username>')
def hello(username):
return render_template('10_hello.html', username=username)
if __name__ == "__main__":
app.secret_key = "Your Key"
app.run(debug=True)
```
<br>
==執行結果如下圖所示:==

可以看到上圖中粗體字是繼承了```base.html```中的標題。從這個範例中發現,透過樣板繼承重新定義了block內的資料,並保留其他結構。透過jinja2樣板繼承的特性除了可以確保整個網站的結構是相同的之外,也能大量減少重複性工作。
<br>
[Source Code Please Visit](https://github.com/ChrisCodeNation/How-to-Make-an-API-with-Flask-Course/blob/main/11_jinja2_template.py)