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 模板引擎的地方。 render_template() 函数可以呈现 HTML 文件,而不是从函数返回硬编码 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 将尝试在 templates 文件夹中查找 HTML 文件,该文件夹与此脚本所在的文件夹相同。

  • Application folder
    • Hello.py
    • templates
      • hello.html

术语"网络模板系统"是指设计一个可以动态插入可变数据的HTML脚本。 Web 模板系统由模板引擎、某种数据源和模板处理器组成。

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

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

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

Next, run the following script from 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 模板系统示例

jinja2 模板引擎使用以下分隔符从 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/resultresult() 函数将字典对象发送到模板 results.html > 在浏览器中打开。

result.html 的模板部分使用 for 循环 将字典对象 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 脚本保存为模板文件夹中的 result.html

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

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

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

Table 表模板示例