標籤:
目前的目錄結構:myblog|----flask|----tmp|----app |----static |----templates |----__init__.py |----views.py|----run.py
編寫第一個模板app/templates/index.html
<html> <title>{{title}} - myblog</title> <body> <h1>Hello,{{user.nickname}}</h1> </body></html>
{{....}}中是變數{%....%}運算式會動態從視圖模板中擷取資料
修改視圖模板 app/views.py
from flask import render_templatefrom app import app@app.route('/')@app.route('/index')def index (): user={'nickname':'Bob'} return render_template("index.html", title="Home", user=user)#從flask匯入render_template#render_template(html檔案,需要傳資料的變數)
模板的判斷語句修改app/templates/index.html
<html> {% if title %} <title>{{title}} - myblog</title> {% else %} <title>Welcome - myblog</title> {% endif %} <body> <h1>Hello,{{user.nickname}}</h1> </body></html>
如果刪除 app/views.py 中 render_template( ) 函數中title參數瀏覽器中的標題就會變成 Welcome - myblog
模板的迴圈語句修改 app/views.py
from flask import render_templatefrom app import app@app.route('/')@app.route('/index')def index (): user={'nickname':'Bob'} posts=[ {'author':{'nickname':'John'}, 'body':'Beautiful day in Portland!'}, {'author':{'nickname':'Susan'}, 'body':'The Avengers movie was so cool!'} ] return render_template("index.html", title="Home", user=user, posts=posts)
修改 app/templates/index.html
<html> {% if title %} <title>{{title}} - myblog</title> {% else %} <title>Welcome - myblog</title> {% endif %} <body> <h1>Hello,{{user.nickname}}</h1> {% for post in posts %} <p>{{ post.author.nickname }} says:<b>{{post.body}}</b></p> {% endfor %} </body></html>
顯示:
模板繼承模板中的固定某部分會多次出現在很多模板中,我們可以單獨做成模板,然後讓需要的模板中繼承
新增一個導覽列模板app/templates/base.html
<html> <head> {% if title %} <title>{{title}} - myblog</title> {% else %} <title>Welcome - myblog</title> {% endif %} </head> <body> <div>MyBlog:<a href="/index">Home</a></div> <hr> {% block content %} {% endblock%} </body></html>
{%block content%}{%endblock%}這兩個運算式之間是新模板可插入的地方
修改 app/templates/index.html
{% extends "base.html" %}{% block content %}<h1>Hello,{{user.nickname}}</h1>{% for post in posts %}<p>{{ post.author.nickname }}says:<b>{{post.body}}</b></p>{% endfor %}{% endblock %}
{%extends 頁面%}這是繼承模板{%block content%}{%endblock%}這兩個運算式之間是可插入內容的地方
顯示:
index.html中多了base.html的內容
flask筆記:3:模板