可以以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 模板引擎。可以从 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将尝试在模板文件夹中找到该脚本所在的文件夹中的HTML文件。
Flask使用 jinja2 模板引擎, Web模板包含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
URL的变量部分插入在 {{name}} 占位符处。
链接:https://www.learnfk.comhttps://www.learnfk.com/flask/flask-templates.html
来源:LearnFk无涯教程网
jinja2 模板引擎使用以下定界符从HTML转义。
在下面的示例中,演示了在模板中使用条件语句,hello()函数的URL规则接受整数参数,它被传递到 hello.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 。
从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和value 放在 {{}}内 。
开发开始运行后,在浏览器中打开 http://localhost:5000/result 以获取以下输出。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)
Tony Bai · Go语言第一课 -〔Tony Bai〕