目录

Flask - 模板

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

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.py
    • templates
      • hello.html

术语'web templating system'指的是设计HTML脚本,其中可以动态插入可变数据。 Web模板系统包括模板引擎,某种数据源和模板处理器。

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

以下代码在templates文件夹中保存为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

URL的variable部分插入{{ name }}占位符。

Web模板系统示例

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

  • {%...%}用于语句
  • {{...}}表达式可以打印到模板输出
  • {#...#}用于注释未包含在模板输出中
  • #... ##用于行语句

在以下示例中,演示了在模板中使用条件语句。 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-elseendif包含在分隔符{%..%}

运行Python脚本并访问URL http://localhost/hello/60 ,然后访问http://localhost/hello/30以查看HTML的输出是否有条件地更改。

Python循环结构也可以在模板中使用。 在以下脚本中,当在浏览器中打开URL http://localhost:5000/result时, result()函数将字典对象发送到模板results.html

result.html的Template部分使用for loop将字典对象result{}键和值对呈现为HTML表的单元格。

从Python shell运行以下代码。

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)

将以下HTML脚本保存为templates文件夹中的result.html

<!doctype html>
<html>
   <body>
      <table border = 1>
         {% for key, value in result.iteritems() %}
            <tr>
               <th> {{ key }} </th>
               <td> {{ value }} </td>
            </tr>
         {% endfor %}
      </table>
   </body>
</html>

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

开发开始运行后,在浏览器中打开http://localhost:5000/result以获得以下输出。

表模板示例
↑回到顶部↑
WIKI教程 @2018