文章主要介绍Flask如何调取html文件作为网页显示,以及如何传达参数给html文件,使其可以动态改变变量的值
环境Windows 工具 vscode anaconda
在Flask中,我们既可以使用python代码产生HTML内容,但在需要变量和条件循环等情况下就需要进行转义这一步操作,个人理解可以等同于很多转义符,需要你特别标记,所以我们使用render_template()函数呈现HTML文件。
代码如下,保存为Flask_template.py
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)
Flask将在文件夹templates下找到对应的hello.html
templates不要命名错误,templates和Flask_template.py放在同一层文件中
再把以下代码在templates文件夹中保存为hello.html
<!doctype html>
<h1>Hello {{ name }}!</h1>
因为Flask使用web templating system,具体就是设计一个HTML脚本,可以动态插入变量数据。该套模板包含了一些变量与表达式的HTML语法占位符,这些可以在呈现该html文件时替换为对应变量的内容,如以上代码中的{ {name} }
运行Flask_template.py后,打开浏览器输入URL:http://127.0.0.1:5000/hello/name,此时URL中的name会插入到html文件中的{ {name} }中
Flask使用的时jinja2模板引擎,在该引擎中由以下几种分隔符用于HTML的转义
- {%……%}用于语句
- {{……}}用于将表达式插入到模板中输出
- {#……#}用于未包含在模板输出的注释
- #……# 用于行语句
在下面的代码中,尝试了使用该模版中的条件语句。
在html文件中保存以下代码,比较URL传输进入的marks和60的大小,注意条件语句都必须放在{%……%}中
<!doctype html>
{% if marks>60 %}
<h1> Your result is pass!</h1>
{% else %}
<h1>Your result is fail</h1>
{% endif %}
在Flask_template.py中写入
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)
运行Python脚本,在浏览器访问URL:http://localhost/hello/scroe(score为你输入的数字),查看显示是否正确