Flask從入門到入土(三)——模板

  模板是一個包含響應文本的文件,其中包含佔位變量表示的動態部分,其具體值只是請求上下文中才能知道。使用真實值替換變量,再返回最終得到的響應字符串,這一過程稱爲渲染。爲了渲染模板,Flask使用了一個名爲Jinja2的強大面板引擎。

Jinja2模板引擎

  形式簡單的Jinja2模板就是一個包含響應文本的文件。

  Flask程序源碼:

 1 from flask import Flask,render_template
 2 
 3 app = Flask(__name__)
 4 
 5 @app.route('/')
 6 def index():
 7     return render_template('index.html')
 8 
 9 @app.route('/user/<name>')
10 def user(name):
11     return render_template('user.html',name=name)
12 
13 if __name__=='__main__':
14     app.run()

    index.html內容:  

1 <h6>hello world</h6>

  user.html內容:

1 <h6>hello,{{name}}!</h6>

  運行結果:

    

      

  結果與之前Flask從入門到入土(二)中結果相同。

使用Flask-Bootstrap集成Twitter Bootstrap

  Bootstrap是一個Twitter的開源框架,它提供的用戶界面組件可以用於創建整潔且具有吸引力的網頁,而且這些網頁還能兼容所有現代Web瀏覽器。

  Bootstrap是客戶端框架,因此不會直接涉及服務器。服務器需要做的只是提供引用了Bootstrap層疊樣式表和Javascript文件的html響應,並在html,css和Javascript代碼中實例化所需組件。這些操作最理想的執行場所就是模板。

  想要在程序中集成Bootstrap,顯然要對模板做所有必要的改動。不過,更簡單的方法是使用一個名爲Flask-Bootstrap的Flask擴展,簡化集成的過程。Flask-Bootstrap使用pip安裝:

1  pip install flask-bootstrap

Flask擴展一般都是在創建實例時初始化。 

  from flask.ext.bootstrap import Bootstrap:专为 Flask 开发的扩展都暴露在 flask.ext 命名空间下,Flask-Bootstrap 输出了一个 Bootstrap 类。

  bootstrap = Bootstrap(app):Flask 扩展一般都在创建程序实例时初始化,这行代码是 Flask-Bootstrap 的初始化方法。

 1 from flask import Flask,render_template
 2 from flask.ext.bootstrap import Bootstrap
 3 
 4 app = Flask(__name__)
 5 bootstrap = Bootstrap(app)
 6 
 7 @app.route('/')
 8 def index():
 9     return render_template('index.html')
10 
11 if __name__ == "__main__":
12     app.run(debug = True) 

  

原文地址:https://www.cnblogs.com/LexMoon/p/Flask_3.html