首先我们看看如何原始的HTML代码插入Flask应用:
from <a href="https://www.gaodaima.com/tag/flask" title="查看更多关于flask的文章" target="_blank">flask</a> import Flask app = Flask(__name__)@app.route('/greet')def greet(): user = {'username': 'John', 'age': "20"} return ''' <<a href="https://www.gaodaima.com/tag/html" title="查看更多关于html的文章" target="_blank">html</a>> <head> <title>Templating</title> </head> <body> <h1>Hello, ''' + user['username'] + '''!, you’re ''' + user['age'] + ''' years old.</h1> </body> </html>'''if __name__ == '__main__': app.run(debug = True,port=8080)
www#gaodaima.com来源gao*daima.com搞@代#码网搞代码
在上面的代码中,我们使用拼接的HTML字符串来展示user字典的数据。现在访问http://127.0.0.1:8080/greet:
拼接HTML字符串非常容易出错,因此Flask使用Jinja 2模板引擎来分离数据逻辑和展示层。
相关推荐:《Python相关教程》
我们将模板文件按如下路径放置:
Apps folder /app.py templates |-/index.html
使用模板时,视图函数应当返回render_template()的调用结果。例如下面的代码片段渲染模板index.html,并将渲染结果作为视图函数的返回值:
from flask import Flask, render_template app = Flask(__name__)@app.route('/hello')def hello(): return render_template('index.html', name="Alex")if __name__ == '__main__': app.run(debug = True)
在上面的代码中,模板文件index.html依赖于变量name,其内容如下:
<html><body> {% if name %} <h2>Hello {{ name }}.</h2> {% else %} <h2>Hello.</h2> {% endif %} </body></html>
模板文件的语法扩充了HTML,因此可以使用变量和逻辑。
在浏览器中访问http://127.0.0.1:8080/hello/alex:
来源:搞代码网:原文地址:https://www.gaodaima.com