《Flask Web Development》第3章 模板

View Function有兩個任務(wù):(1)處理業(yè)務(wù)邏輯 (2)返回響應(yīng)內(nèi)容。將兩者分開管理能夠使代碼更好容易維護,模板起的就是這么一個作用。本章介紹的模板引擎Jinjia2(注:如果開發(fā)中前端使用AngularJS或者不適用Flask提供的模板,那么如下內(nèi)容可以跳過了)。

Jinjia模板引擎

模板只是一些包含文本的字符串,設(shè)置的變量標(biāo)記位最終會被模板引擎用數(shù)據(jù)替換。要使用Jinjia模板,第一步是定義模板,Jinjia2默然會到templates子目錄中尋找模板,所以在該目錄下定義兩個模板文件:

templates/index.html:

<h1>Hello World!</h1>

templates/user.html

<h1>Hello {{name}}!</h1>
渲染模板

如下例子導(dǎo)入渲染模板的方法,然后調(diào)用模板方法去注入模板:

index.py

from flask import Flask, render_template

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

@app.route('/<name>')
def user(name):
    return render_template('user.html', name=name)

啟動server以后可以分別訪問相對路徑/index/<name>索引來查看頁面內(nèi)容結(jié)果。

變量類型

模板中除了接受普通變量,還能接收復(fù)雜的數(shù)據(jù)結(jié)構(gòu),比如dict、list、obj,修改后的模板如下:

templates/user.html:

<p>A value from a dictionary: {{ mydict['key'] }}.</p>
<p>A value from a list: {{ mylist[3] }}.</p>
<p>A value from a list, with a variable index: {{ mylist[myintvar] }}.</p>
<p>A value from an object's method: {{ myobj.somemethod() }}.</p>

那么對應(yīng)的在python就要定義一些數(shù)據(jù)結(jié)構(gòu):

index.py

class Human():
    def somemethod(self):
        return 'what the fucking world!'

@app.route('/<name>')
def user(name):
    mydict = {"key": "To Be or Not To Be"}
    mylist = ['it', 'is', 'a', 'problem']
    myintvar = 0
    myobj = Human()

    return render_template('user.html', name=name, mydict=mydict, mylist=mylist, myintvar=myintvar, myobj=myobj)

可以執(zhí)行index.py來查看運行結(jié)果。

除了使用復(fù)雜的數(shù)據(jù)結(jié)構(gòu)以外,模板中還能使用過濾器對內(nèi)容進行過濾,下面是一個將字符內(nèi)容變?yōu)榇髮懙睦樱?/p>

 Hello, {{ name|capitalize }}
控制結(jié)構(gòu)

Jinjia2能夠使用常見的控制流,如下是常用的集中控制流的簡要介紹:

  • If控制流

index.py

@app.route('/flow')
def flow():
    user = 'tangyefei'

    return render_template('flow.html', user=user)

templates/flow.html

{% if user %}
    Hello, {{user}}
{% else %}
    Hello, stranger
{% endif %}
  • Loop控制流

index.py

@app.route('/loop')
def loop():
    comments = ["To Be", "Or", "Not To Be"]

    return render_template('loop.html', comments=comments)

templates/loop.html

<ul>
    {% for comment in comments%}
        <li>{{comment}}</li>
    {% endfor %}
</ul>
  • Macro

index.py

@app.route('/macro')
def macro():
    comments = ["To Be", "Or", "Not To Be"]

    return render_template('macro.html', comments=comments)

templates/macro.html

{% macro render_comment(comment) %}
    <li>{{comment}}</li>
{% endmacro %}

<ul>
     {% for comment in comments%}
        {{ macro.render_comment(comment) }}
    {% endfor %}
</ul>
  • 外部導(dǎo)入Macro

index.py

@app.route('/comments')
def comments():
    comments = ["To Be", "Or", "Not To Be"]

    return render_template('comments.html', comments=comments)

templates/macro.html

{% macro render_comment(comment) %}
    <li>{{comment}}</li>
{% endmacro %}

templates/comments.html

{% import 'macro.html' as macro %}
<ul>
     {% for comment in comments%}
        {{ macro.render_comment(comment) }}
    {% endfor %}
</ul>
  • 模板繼承

index.py

@app.route('/extends')
def extends():
    return render_template('child.html')

/templates/base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    {% block head%}
        <title>
            {% block title%}{% endblock%}- My Application
        </title>
    {% endblock %}
</head>
<body>
    {% block body%}
    {% endblock%}
</body>
</html>

/templates/child.html

{% extends 'base.html'%}

{% block title%}
    Index
{% endblock %}

{% block head%}
    {{ super() }}
    <style>
    </style>
{% endblock%}

{% block body%}
    <h1>Helll, World!</h1>
{% endblock%}

集成Bootstrap

要使用Bootstrap,最直觀的辦法是引入對應(yīng)的css和js文件,在Flask中只需要安裝Flask-Bootstrap,然后在模板中繼承base.html就可以使用Bootstrap。如下為安裝和使用的一個詳細(xì)的例子:

  • 第一步,安裝flask-bootstrap
(venv) $ pip install flask-bootstrap
  • 第二步,Python文件中使用Bootstrap
# 引入flask-bootstrap
from flask.ext.bootstrap import Bootstrap

# 包裹app
bootstrap = Bootstrap(app)

# 定義View Function
@app.route('/bootstrap/<name>')
def bootstrap(name):
    return render_template('bootstrap.html', name=name)
  • 第三步,構(gòu)建模板覆寫提供的三個block
{% extends 'bootstrap/base.html'%}

{% block title%} Flasky {% endblock %}
{% block navbar%}

    <div class="navbar navbar-inverse" role="navigation">
        <div class="container">
            <div class="navbar-header">
            <button type="button" class="navbar-toggle"
            data-toggle="collapse" data-target=".navbar-collapse">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
           </button>
            <a class="navbar-brand" href="/">Flasky</a> </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li><a href="/">Home</a></li>
                </ul>
            </div>
        </div>
    </div>
{% endblock %}
{% block content%}
    <div class="container">
        <div class="page-header">
        <h1>Hello, {{ name }}!</h1> </div>
    </div>
{% endblock %}


Bootstrap還定義了一些其他的Block能夠被覆寫的,比如下面的例子是一個覆寫block script的例子:

{% block scripts %}
    {{ super() }}
    <script type="text/javascript" src="my-script.js"></script>
{% endblock %}

定制錯誤頁面

Flask允許我們基于template來定制錯誤頁面:

@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404

@app.errorhandler(500)
def internal_server_error(e):
    return render_template('500.html'), 500

因為我們引入了Bootstrap,為了保證界面一致性你可能會想直接拷貝Bootstrap的base.html頁面來修改一個 404.html。但是更簡單的做法是,基于Bootstrap的base.html定制一個tempates/base.html,將一些項目通用的內(nèi)容放在里面,然后項目頁面比如 404.html基礎(chǔ)都以此為基礎(chǔ):

templates/base.html

{% extends "bootstrap/base.html" %}

{% block title %}Flasky{% endblock %}
{% block navbar %}
<div class="navbar navbar-inverse" role="navigation">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="/">Flasky</a>
        </div>
        <div class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
                <li><a href="/">Home</a></li>
            </ul>
        </div>
    </div>
</div>
{% endblock %}

{% block content %}
    <div class="container">
        {% block page_content %}{% endblock %}
    </div>
{% endblock %}

templates/404.html

{% extends 'commonBase.html'%}

{% block title%} Page Not Found{% endblock%}
{% block content %}
    <div class="page-header">
        <h1>Not Found</h1>
    </div>
{% endblock%}

可以嘗試訪問一個不存在的地址,看頁面是否定位到了我們定制的404頁面。

請求跳轉(zhuǎn)

在代碼中我們可能會想獲取某個路由,因為很多路由都有參數(shù),一旦路由參數(shù)發(fā)生變化,直接獲取路由的代碼就需要更新來保證仍能正常工作。

為此Flask提供了一個工具方法 url_for 用來做獲取View Function所對應(yīng)的路由,注意該方法只是用來獲取url而不是做跳轉(zhuǎn)的方法:

url_for('user', name='john', _external=True)

該方法會將多余參數(shù)憑借到url后面:

# would return /?page=2.
url_for('index', page=2)  

靜態(tài)文件

在Flask中,靜態(tài)文件會從根目錄中的static下去尋找。如下是一個使用圖片作為瀏覽器Tab的Icon的例子,圖片可以在Flasky項目中找:

templates/base.html 添加代碼片段

{% block head %}
    {{ super() }}
    <link rel="shortcut icon" href="{{ url_for('static', filename = 'favicon.ico') }}" type="image/x-icon">
    <link rel="icon" href="{{ url_for('static', filename = 'favicon.ico') }}" type="image/x-icon">
{% endblock %}

本地化時間和日期

用戶遍及在世界各地,因此統(tǒng)一用UTC來表示時間日期。但是在每個客戶端,用戶所看到的時間格式應(yīng)該有所不同。這個工作最適合交給客戶端-瀏覽器來做,因為瀏覽器能獲取到用戶的地區(qū)和語言設(shè)置。

有這么一個客戶端的js庫叫moment.js實現(xiàn)了很多時間日期處理相關(guān)的方法,在Flask中可以通過安裝flask-moment來使用它。如下是使用的例子:

  • 第一步,安裝
(venv)$ pip install flask-moment
  • 第二步,在Python中導(dǎo)入

index.py

# 導(dǎo)入moment和local的datetime
from flask.ext.moment import Moment
from datetime import datetime
#...
moment = Moment(app)
#...
@app.route('/')
def index():
    return render_template('index.html', current_time=datetime.utcnow())
  • 第三步,在頁面中引入和使用

templates/base.html

{% block scripts %}
{{ super() }}
{{ moment.include_moment() }}
{% endblock %}

templates/index.html

<p>The local date and time is {{ moment(current_time).format('LLL') }}.</p>
<p>That was {{ moment(current_time).fromNow(refresh=True) }}</p>

moment.js實現(xiàn)了format()、fromNow()、 fromTime()等方法,使用這些方法基本能夠構(gòu)建出友好的客戶端代碼了。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容