栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

flask浅学(3)[模板渲染]

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

flask浅学(3)[模板渲染]

@TOC

返回正常html网页

1.在templates目录下新建about.html网页

2.编写对应的视图函数,引入新的方法render_template,用来返回html格式的页面

@app.route('/about')
def about():
    context = {
        'username': '张三'
    }
    return render_template('about.html', **context)

3.在html中标记对应的名字的位置 {{ username}} ,模板语言的标记方法,




    
    Title



    

这里是名字{{ username }}

成果展示

jinja2模板过滤器
通过语法过滤数据有几个字符

    

这里是名字{{ username|length }}

join过滤器,将列表中的多个元素,变成字符串类型

{{ books|join('//') }}

# 这样展示的就是 一整个字符串

控制语句,分为if语句和for语句

@app.route('/control/')
def control(age):
	# 接收前端传入的年龄
    context = {
        "age": age,
        'books': ['1', 2, 3, 4, 5]
    }
    return render_template('control.html', **context)
# 前端页面中进行判断,根据age的大小进行不同的展示,注意要点是要有结束的endif
{% if age > 18 %}
    
你已经成年
{% elif age < 18 %}
你没有成年
{% elif age == 18 %}
你刚好成年
{% endif %}

for语句

@app.route('/control/')
def control(age):
	# 接收前端传入的年龄
    context = {
        "age": age,
        'books': ['1', 2, 3, 4, 5]
    }
    return render_template('control.html', **context)
# 根据后端传过来的列表数据,进行循环,然后展示
    {% for i in books %}
  • {{ i }}
  • {% endfor %}

成果

当需要循环的参数为字典类型时

def control(age):
    context = {
        "age": age,
        'books': ['1', 2, 3, 4, 5],
        'person': {'name': 'lll', 'age': 18}
    }
    return render_template('control.html', **context)
    {% for l1, l2 in person.items() %}
    {{ l1 }}:{{ l2 }}
    {% endfor %}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/753381.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号