Flask框架学习笔记之模板操作实例详解

yipeiwu_com6年前Python基础

本文实例讲述了Flask框架学习笔记之模板操作。分享给大家供大家参考,具体如下:

flask的模板引擎是Jinja2。

引入模板的好处是增加程序的可读性和易维护性,从而不用将一堆html代码塞在视图函数中。

还是以hello world为例。最基础的调用模板修饰文本。

# 根网址
@app.route('/')
def index():
  # return render_template("index.html")
  # 可以给模板传入文本content修饰
  content = "Hello World!"
  return render_template("index.html", content = content)

index模板,用{{}}表示变量。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
  <!--<h1>Hello World!</h1>></!-->
  <h1>{{ content }}</h1>
</body>
</html>

这里定义一个类以传入变量。

class User(object):
  def __init__(self, user_id, user_name):
    self.user_id = user_id
    self.user_name = user_name

传参

# 通过调用类的实例方法给模板传递参数修饰
@app.route('/user')
def user_index():
  user = User(520, "loli")# user_id, user_name
  return render_template("user_index.html", user=user)

user_index模板,仅显示user_name。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
  <h1>Hello {{ user.user_name }}</h1>
</body>
</html>

在模板中实现if语句

# 在模板中使用if语句
@app.route('/query_user/<user_id>')
def query_user(user_id):
  user = None
  # 如果传入的id为520则调用实例
  if int(user_id) == 520:
    user = User(520, 'loli')

  return render_template("user_id.html", user=user)

user_id模板,用{% %}包裹if语句,若user不为None(也就是传入了name),则显示if下语句,否则显示else下语句。

最后一定要加上{% endif %}表示判断语句结束。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
  {% if user %}
    <h1>hello {{ user.user_name }}</h1>
  {% else %}
    <h1>no this user</h1>
  {% endif %}

</body>
</html>


在模板中使用for循环语句

@app.route('/users')
def user_list():
  users = []
  for i in range(1, 11):
    user = User(i, "loli" + str(i))
    users.append(user)# 将user添加到users
  return render_template("user_list.html", users = users)# 在模板中修饰users

user_list模板,同样的,for循环语句也要用{% %}包裹起来,需要用{% endfor %}表示for循环结束。这里传入id和name两个参数。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
  {% for user in users %}
    {{ user.user_id }} -- {{ user.user_name }}<br>
  {% endfor %}
</body>
</html>

模板的继承。模板继承的初衷也是为了代码更加简单,更易维护,将相同部分的代码提到一个基类模板,有点类似于类的继承。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
  <div>
    <h1>I love you {{ user.user_name }}</h1>
  </div>
  {% block content %}
  {% endblock %}
  <div>
    <h1>So much!</h1>
  </div>
</body>
</html>

用<div>圈起来的是不可变的父模板,可改动添加的部分在{% block content %}{% endblock %}之间。

子模版,用{% extends "父模板" %} 表示从父模板继承了代码。在{% block content %}{% endblock %}之间添加内容。

{% extends "base.html" %}
{% block content %}
  <h2>more than anyone</h2>
{% endblock %}
{% extends "base.html" %}
{% block content %}
  <h2>more than anything</h2>
{% endblock %}

调用

# 模板继承1
@app.route('/one')
def one_base():
  user = User(520, 'loli')
  return render_template("one_base.html", user=user)
# 模板继承2
@app.route('/two')
def two_base():
  user = User(520, 'loli')
  return render_template("two_base.html", user=user)


可以看到子模版继承了题头和尾部,中间为子模版添加的内容。

代码

#-*- coding:utf-8 -*-
from flask import Flask, render_template# 导入render_template以使用模板
# 定义一个models导入一个有id和name的类
from models import User

app = Flask(__name__)
# 根网址
@app.route('/')
def index():
  # return render_template("index.html")
  # 可以给模板传入文本content修饰
  content = "Hello World!"
  return render_template("index.html", content = content)
# 通过调用类的实例方法给模板传递参数修饰
@app.route('/user')
def user_index():
  user = User(520, "loli")
  return render_template("user_index.html", user=user)
# 在模板中使用if语句
@app.route('/query_user/<user_id>')
def query_user(user_id):
  user = None
  if int(user_id) == 520:
    user = User(520, 'loli')

  return render_template("user_id.html", user=user)
# 在模板中使用for循环语句
@app.route('/users')
def user_list():
  users = []
  for i in range(1, 11):
    user = User(i, "loli" + str(i))
    users.append(user)
  return render_template("user_list.html", users = users)
# 模板继承1
@app.route('/one')
def one_base():
  user = User(520, 'loli')
  return render_template("one_base.html", user=user)
# 模板继承2
@app.route('/two')
def two_base():
  user = User(520, 'loli')
  return render_template("two_base.html", user=user)

if __name__ == '__main__':
  app.run()

希望本文所述对大家基于flask框架的Python程序设计有所帮助。

相关文章

Python删除指定目录下过期文件的2个脚本分享

脚本1: 这两天用python写了一个删除指定目录下过期时间的脚本。也可能是我初学python,对python还不够熟习,总觉得这个脚本用shell写应该更简单也更容易些。就功能上来说,...

ActiveMQ:使用Python访问ActiveMQ的方法

ActiveMQ:使用Python访问ActiveMQ的方法

Windows 10家庭中文版,Python 3.6.4,stomp.py 4.1.21 ActiveMQ支持Python访问,提供了基于STOMP协议(端口为61613)的库。 Act...

Python中Collections模块的Counter容器类使用教程

Python中Collections模块的Counter容器类使用教程

1.collections模块 collections模块自Python 2.4版本开始被引入,包含了dict、set、list、tuple以外的一些特殊的容器类型,分别是: Order...

python嵌套字典比较值与取值的实现示例

python嵌套字典比较值与取值的实现示例

前言 本文通过示例给大家介绍了python嵌套字典比较值,取值,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。 示例代码 #取值import types allGu...

Python小工具之消耗系统指定大小内存的方法

工作中需要根据某个应用程序具体吃了多少内存来决定执行某些操作,所以需要写个小工具来模拟应用程序使用内存情况,下面是我写的一个Python脚本的实现。 #!/usr/bin/pytho...