小福利,flask框架学习笔记(3)

本文介绍了使用Flask框架进行条件判断和循环操作的方法,展示了如何在Python后端和HTML模板中实现这些功能。同时,讲解了自定义模板过滤器的创建和使用,以及宏的定义与应用,帮助读者深入理解Flask模板引擎的灵活性和实用性。
摘要由CSDN通过智能技术生成

大家好,我是天空之城,今天给大家带来小福利,flask框架学习笔记(3)
条件判断和for循环
py文件

from flask import Flask, render_template


app = Flask(__name__)

context = {
    'username': 'jerry',
    'age': 18,
    'books': ['Python', 'Java', 'PHP'],
    'book': {'Python': 666,
             'Java': 777,
             'PHP': 888
             }
}


@app.route('/')
def if_for():
    return render_template('if_for.html', **context)


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


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


html文件

{% import 'macro.html' as macro with context %}
{% from 'macro.html' import input %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{{ input('password', type='password') }}
{{ macro.input('username') }}
    {% if username == 'cheney' %}
        <p>{{ username }}</p>
    {% else %}
        <p>当前用户不是cheney</p>
    {% endif %}

    {% for book in books %}
        <p>{{ book }}</p>
    {% endfor %}
    <hr>

    {% for i in book %}
        <p>{{ i }}</p>
    {% endfor %}
    <hr>
    {% for key, value in book.items() %}
        <p>{{ key }}</p>
        <p>{{ value }}</p>
    <hr>
    {% endfor %}

    <hr>
    {% for book in books %}
        <p>{{ book }}</p>
        <p>{{ loop.index0 }}</p>
        <p>{{ loop.first }}</p>
    {% endfor %}
</body>
</html>


自定义过滤器
py文件

from flask import Flask, render_template
from datetime import datetime

app = Flask(__name__)


@app.route('/')
def index():
    context = {
        'username': 'hello cheney',
        'age': -18,
        'home': '湖南',
        'name': 'logic',
        'es': "<script>alert('hello');</script>",
        'books': ['Python', 'Java', 'PHP'],
        'book': {'Python': 666},
        'address': '中国 湖南省 长沙市 岳麓区 高新区',
        'now_time': datetime(2020, 10, 14, 21, 7, 0)
    }
    return render_template('index.html', **context)


@app.template_filter('my_filter')
def my_filter(value):
    return value.replace('hello', '')


@app.template_filter('handler_time')
def handler_time(time):
    """
    小于一分钟---->刚刚
    大于一分钟小于一小时---->xxx分钟之前
    大于一小时小于24小时----> xxx小时之前
    """
    now = datetime.now()
    # 获取总秒数
    timestamp = (now - time).total_seconds()

    if isinstance(time, datetime):
        if timestamp < 60:
            return '刚刚'
        elif 60 <= timestamp <= 60*60:
            return '%s分钟之前' % int(timestamp/60)
        elif 60*60 < timestamp <= 60*60*24:
            return '%s小时之前' % int(timestamp/(60*60))
    else:
        return time


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


html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>首页</h1>
    <p>{{ username }}</p>
    <p>{{ age|abs }}</p>
    <p>{{ name|default('这个人很懒,什么都没有留下') }}</p>
    <!--  关闭转义功能  -->
    {# {% autoescape off %}
    <p>{{ es }}</p>
    {% endautoescape %} #}

    {# <p>{{ es|safe }}</p> #}
    <p>{{ books|first }}</p>
    <p>{{ books|last }}</p>
    <p>{{ books|length }}</p>
    <p>{{ book|length }}</p>
    <p>{{ books|first|length }}</p>
    <p>{{ username|replace('cheney', 'jerry') }}</p>
    <p>{{ username|truncate(length=5) }}</p>
    <p>{{ es|striptags }}</p>
    <p>{{ address|wordcount }}</p>
    <p>{{ username|my_filter }}</p>
    <p>博客发表时间:{{ now_time|handler_time }}</p>


</body>
</body>
</html>


宏的使用–代码的复用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    {% macro input(name, value='', type='text') %}
    <input type="{{ type }}", name="{{ username }}", value="{{ value }}">
    {% endmacro %}
<!--    <table>-->
<!--        <tr>-->
<!--            <td>用户名:</td>-->
<!--            <td>{{ input('username') }}</td>-->
<!--        </tr>-->

<!--        <tr>-->
<!--            <td>密码:</td>-->
<!--            <td>{{ input('password', type='password') }}</td>-->
<!--        </tr>-->
<!--    </table>-->
</body>
</html>


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值