Flask框架如何使用HTML模板

671次阅读
没有评论

Flask框架如何使用HTML模板

首先我们看看如何原始的HTML代码插入Flask应用:

from flask import Flask
app = Flask(__name__)@app.route('/greet')def greet():
    user = {'username': 'John', 'age': "20"}    return '''
<html>
    <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)

在上面的代码中,我们使用拼接的HTML字符串来展示user字典的数据。现在访问http://127.0.0.1:8080/greet:

Flask框架如何使用HTML模板

拼接HTML字符串非常容易出错,因此Flask使用Jinja 2模板引擎来分离数据逻辑和展示层。

我们将模板文件按如下路径放置:

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:

Flask框架如何使用HTML模板

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2019-10-22发表,共计1263字。
新手QQ群:570568346,欢迎进群讨论 Python51学习
评论(没有评论)