Flask - 模板

可以以HTML的形式返回绑定到某个URL的函数的输出.例如,在以下脚本中, hello()函数将呈现'Hello World'并附加< h1> 标记.

from flask import Flask
app = Flask(__name__)

@app.route('/')
def index():
   return '<html><body><h1>Hello World</h1></body></html>'

if __name__ == '__main__':
   app.run(debug = True)


但是,从Python代码生成HTML内容是很麻烦,特别是当需要放置变量数据和Python语言元素(如条件或循环)时.这需要经常从HTML中转义.

这是人们可以利用Flask所基于的 Jinja2 模板引擎的地方.不是从函数返回硬编码HTML,而是可以通过 render_template()函数呈现HTML文件.

from flask import Flask
app = Flask(__name__)

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

if __name__ == '__main__':
   app.run(debug = True)


Flask将尝试在模板文件夹中找到HTML文件,该文件夹位于存在此脚本的同一文件夹中.

  • 应用程序文件夹

    • hello.html

    • Hello.py

    • templates

术语'网络模板系统'是指设计一个HTML脚本,其中可以动态插入变量数据. Web模板系统包括模板引擎,某种数据源和模板处理器.

Flask使用 jinga2 模板引擎. Web模板包含用于变量和表达式(在这些情况下为Python表达式)的HTML语法散布占位符,它们在呈现模板时被替换为值.

以下代码保存为 hello模板文件夹中的.html .

<!doctype html>
<html>
   <body>
   
      <h1>Hello {{ name }}!</h1>
      
   </body>
</html>


接下来,从Python shell运行以下脚本.

from flask import Flask, render_template
app = Flask(__name__)

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

if __name__ == '__main__':
   app.run(debug = True)


当开发服务器开始运行时,打开浏览器并输入URL作为 :   http://localhost:5000/hello/mvl

网址的变量部分插入 {{name 占位符.

网页模板系统示例

Jinga2 模板引擎使用以下分隔符从HTML中转义.

  • {%...% } for Statements

  • {{...}}表达式打印到模板输出

  • {#...#} for Comments not not包含在模板输出中

  • #... ##用于行语句

在以下示例中,使用演示了模板中的条件语句. hello()函数的URL规则接受整数参数.它被传递给 hello.html 模板.在其中,比较接收的数字(标记)的值(大于或小于50),因此有条件地呈现HTML.

Python脚本如下 :

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/hello/<int:score>')
def hello_name(score):
   return render_template('hello.html', marks = score)

if __name__ == '__main__':
   app.run(debug = True)


hello.html 的HTML模板脚本如下 :

<!doctype html>
<html>
   <body>
      {% if marks>50 %}
         <h1> Your result is pass!</h1>
      {% else %}
         <h1>Your result is fail</h1>
      {% endif %}
   </body>
</html>


请注意,条件语句 if-else endif 包含在分隔符 { %..%} .

运行Python脚本并访问URL http://localhost/hello/60 然后 http ://localhost/hello/30 可以看到HTML的输出有条件地改变.

Python循环结构也可以在模板中使用.在以下脚本中, result()函数在URL http://localhost:5000/result  results.html >在浏览器中打开.

result.html 的模板部分使用 for循环来呈现键和值对字典对象结果{} 作为HTML表格的单元格.

从Python shell运行以下代码.

 
来自flask导入Flask,render_template 
 app = Flask(__ name__)
 @ app.route('/result')
 def result( ):
 dict = {'phy':50,'che':60,'maths':70} 
返回render_template('result.html',result = dict)
如果__name__ =='__ main__':
 app.run(debug = True)


将以下HTML脚本保存为结果模板文件夹中的.html .

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/result')
def result():
   dict = {'phy':50,'che':60,'maths':70}
   return render_template('result.html', result = dict)

if __name__ == '__main__':
   app.run(debug = True)


这里,对应于 For 循环的Python语句再次包含在{%..%}中,而表达式键和值放在 {{}} 中.

开发开始运行后,打开 http://localhost :5000/结果在浏览器中获取以下输出.

表模板示例