參考來源:The Flask Mega-Tutorial Part III: Web Forms
- 由最基本的base.html開始:
<!DOCTYPE html> <html> <head> {% if title %} <title>{{ title }}</title> {% else %} <title>歡迎來到小波的心得</title> {% endif %} </head> <body> <div> 小波的心得: <a href="{{ url_for('index') }}">首頁</a> <!--傳回index函式所在的網址--> <a href="{{ url_for('login') }}">登入</a> <!--傳回login函式所在的網址--> </div> <hr> {% with messages = get_flashed_messages() %} <!--使用閃爍訊息--> {% if messages %} <ul> {% for message in messages %} <li>{{ message }}</li> {% endfor %} </ul> {% endif %} {% endwith %} {% block content %}{% endblock %} </body> </html>
可以觀察到,除了原本的html header以外,有以下的特殊格式可以將原本的base.html拓展給其他template使用,至於{{ url_for(‘index’) }}這類的用法下次再補充:
- templates之間的拓展主要靠以下兩種語法
- {% extends “base.html” %}
- {% block content %}…{% endblock %}
- 還有三種特殊用法(可用巢狀迴圈)
- if-else:{% if 變數 %}…{% else %}…{% endif %}
- with:{% with 變數 %}…{% endwith %}
- for loop:{% for 變數 in 集合 %}…{% endfor %}。
- templates之間的拓展主要靠以下兩種語法
- 再衍生出index.html:
{% extends "base.html" %} {% block content %} <h1>Hi, {{ user.username }}!</h1> {% for post in posts %} <div><p>{{ post.author.username }} says: <b>{{ post.body }}</b></p></div> {% endfor %} {% endblock %}
- 或者是login.html(以此類推):
{% extends "base.html" %} {% block content %} <h1>Sign In</h1> <form action="" method="post"> {{ form.hidden_tag() }} <p> {{ form.username.label }}<br> {{ form.username(size=32) }}<br> {% for error in form.username.errors %} <span style="color: red;">[{{ error }}]</span> {% endfor %} </p> <p> {{ form.password.label }}<br> {{ form.password(size=32) }}<br> {% for error in form.password.errors %} <span style="color: red;">[{{ error }}]</span> {% endfor %} </p> <p>{{ form.remember_me() }} {{ form.remember_me.label }}</p> <p>{{ form.submit() }}</p> </form> {% endblock %}
此處用到許多form的method,下次再整理。