python web框架Flask学习笔记(四)模板的变量

python web框架Flask学习笔记(四)模板的变量

redballoon
2022-11-13 / 0 评论 / 14 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2023年02月20日,已超过36天没有更新,若内容或图片失效,请留言反馈。

简介

flask.jpg
模板中的变量是一种特殊的占位符,是用来告诉模板引擎,该位置的值是从渲染模板时传递的数据中来获取的。

通过render_template('xxx.html', 变量名1=变量值1,变量名2=变量值2 ...)来传递变量的值。

变量在模板中的表示

在模板中占位变量的表示 : {{变量名}}

在 flask 程序中:

from flask import Flask, render_template

app = Flask(__name__)


@app.route('/first')
def index():
    return render_template('FirstTemplate.html', title='My First Template', )


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

在html文件(模板文件)中:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{title}}</title>
</head>
<body>
<h1>This is {{title}}</h1>
</body>
</html>

运行试试吧,😀如果没问题你会看到
运行结果

复杂类型的变量传参

这只是简单字符串类型的传递,如果需要列表,字典等又该怎么操作呢?如果需要传入的变量有很多,都写在 render_template 里会不会显得代码不美观且臃肿?

为避免将所有占位变量都写在 render_template 中,通常在视图函数中定义好要动态传递的变量,再通过 locals() 方法,它会以字典的方式创建一个变量,局部变量名为 key 值为value的形式存储。

示例:

flask程序:

from flask import Flask, render_template

app = Flask(__name__)


@app.route('/first')
def index():
    title = 'Hello World'
    content = '我是内容我是内容我是内容。。。'
    return render_template('FirstTemplate.html', info=locals())


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

模板文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{info.title}}</title>
</head>
<body>
<h1>This is content:{{info.content}}</h1>
</body>
</html>

在模板中通过 {{info.占位变量}} 来引用变量,是不是简单多了,再多的变量,都可以以这种方式来获取。

或者是直接 **locals() 来把变量封装,在模板中就直接使用 {{占位变量}} 也是一样的实现效果

执行结果:
执行结果

复杂数据类型

flask程序

class LOLHero(object):
    def __init__(self):
        self.name = None
        
    def say(self):
        return '这是{self.name}的信息...'


@app.route('/index')
def index():
    # 字符串类型
    title = '不同数据类型的模板传参'
    # 列表类型
    lists_data = ['提莫', '璐璐', '小法师', '小炮手', '波比']
    # 元组类型
    tuples_data = ('疾风剑豪', '暗裔剑魔', '无双剑姬', '无极剑圣')
    # 字典类型
    dicts_data = {
        '疾风剑豪': '亚索',
        '暗裔剑魔': '亚托克斯',
        '无双剑姬': '菲奥娜',
        '无极剑圣': '易',
    }
    # 类方法 (对象)
    hero = LOLHero()
    hero.name = '无敌盖伦'

    return render_template('differentDataTemplate.html', test_data=locals())

模板文件:

<!--获取列表中的第1个元素-->
<h2>list中第1个元素:{{test_data.lists_data.0}}</h2>
<h2>list中第1个元素:{{test_data.lists_data[0]}}</h2>
<!--两种方式都可以-->
<!--获取元组中的第3个元素-->
<h2>tuple中第3个元素:{{test_data.tuples_data[2]}}</h2>
<!--获取字典中键为 '无极剑圣' 的值-->
<h2>dict中键为 '无极剑圣' 的值:{{test_data.dicts_data['无极剑圣']}}</h2>
<!--获取类对象LOLHero中的 name 属性值-->
<h2>LOLHero的name属性: {{test_data.hero.name}}</h2>
<!--调用类对象LOLHero的 say 方法-->
<h2>LOLHero的 say 方法: {{test_data.hero.say()}}</h2>

执行结果:
执行结果

url_for()在模板中的使用

flask程序:

from flask import Flask, render_template

app = Flask(__name__)


@app.route('/')
def index():
    return render_template('yyy.html')


@app.route('/login')
def login():
    return '这是登录页面...👋'


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

模板文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h2><a href="{{url_for('login')}}">点击登录</a></h2>
</body>
</html>

运行就可以看见当我们鼠标移动到 点击登录 上时,会在页面左下角显示反向解析的路径,也可以打开开发者工具查看 是 /login 的格式。

0

评论 (0)

取消