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中使用模板》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

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

Collective Intelligence实战

Collective Intelligence实战

阿拉克 / 2010-9 / 58.00元

《Collective Intelligence实战》内容简介:在互联网上,利用用户的集体智慧是成功的关键。集体智慧是一种新兴的编程技术,可让您从人们访问web和与web交互的过程中找到有价值的模式、发现这些访问者之间的关系和确定他们的个人偏好及习惯等。《collective Intelligence实战》首先介绍了集体智慧的原则和构建更具交互性网站的思想,然后通过示例开发了一个直接可用的基于Ja......一起来看看 《Collective Intelligence实战》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具