flask中使用模板

栏目: Python · 发布时间: 6年前

内容简介:创建一个模板文件app/templates/index.html,内容如下jinja2模板引擎使用{{….}} 来获取视图函数传来的变量在视图函数中渲染模板app/views.py,内容如下

创建一个模板文件app/templates/index.html,内容如下

jinja2模板引擎使用{{….}} 来获取视图函数传来的变量

<html>
  <head>
    <title>{{title}} - blog</title>
  </head>
  <body>
      <h1>Hello, {{user.nickname}}!</h1>
  </body>
</html>

在视图函数中渲染模板app/views.py,内容如下

render_template是渲染模板,第一个参数是需要渲染的模板文件,模板文件默认是app目录下的templates目录,要对模板传入flask的变量通过关键字参数的方式传入

from flask import render_template
from app import app

@app.route('/')
@app.route('/index')
def index():
    user = { 'nickname': 'zdz' } # fake user
    return render_template("index.html", title = 'Home',user = user)

在模板中使用控制语句,控制语句写在 {% …. %} 中,修改app/templates/index.html,内容如下

<html>
  <head>
    {% if title %}
    <title>{{title}} - blog</title>
    {% else %}
    <title>Welcome to blog</title>
    {% endif %}
  </head>
  <body>
      <h1>Hello, {{user.nickname}}!</h1>
  </body>
</html>

修改视图函数app/views.py,内容如下

def index():
    user = { 'nickname': 'zdz' }
    posts = [
        {
            'author': { 'nickname': '张三' },
            'body': '张三'
        },
        {
            'author': { 'nickname': '李四' },
            'body': '李四'
        }
    ]
    return render_template("index.html",
        title = 'Home',
        user = user,
        posts = posts)

在模板中使用循环语句,视图函数将posts这个变量作为列表传入模板,模板可以使用字典或者对象的方式获取传入的变量的值。

<html>
  <head>
    {% if title %}
    <title>{{title}} - blog</title>
    {% else %}
    <title>blog</title>
    {% endif %}
  </head>
  <body>
    <h1>Hi, {{user.nickname}}!</h1>
    {% for post in posts %}
    <p>{{post.author.nickname}} says: <b>{{post.body}}</b></p>
    {% endfor %}
  </body>
</html>

以上所述就是小编给大家介绍的《flask中使用模板》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Web Data Mining

Web Data Mining

Bing Liu / Springer / 2011-6-26 / CAD 61.50

Web mining aims to discover useful information and knowledge from Web hyperlinks, page contents, and usage data. Although Web mining uses many conventional data mining techniques, it is not purely an ......一起来看看 《Web Data Mining》 这本书的介绍吧!

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

html转js在线工具
html转js在线工具

html转js在线工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具