【Flask专题】12.模板-循环loop和宏(PyCharm)

12 篇文章 0 订阅
11 篇文章 0 订阅

模板-循环loop和宏(PyCharm)


模板中:
声明变量:
{{ set a=10 }}
使用变量:
{{ a }}
类型:
过滤器:字符串、数字、列表、字典…
流程控制:
{% if %}…{% endif %}
{% for n in data %}…{% endfor %}
函数:
{% macro 宏名(参数) %}
使用各种模板语法:for、if… + html标签
{% endmacro %}
继承:
父模板:base.html
在父模板中预设block
子模板:{% extends ‘base.html’ %}
填充block

loop.index、loop.index、loop.lenth例举

loop.index:当前循环迭代的次数(从1开始)
loop.index0:当前循环迭代的次数(从0开始)
loop.revindex:到循环结束需要迭代的次数(从1开始)
loop.revindexo:到循环结束需要迭代的次数(从0开始)
loop.last:如果是最后一次迭代,为True
loop.first:如果是第一次迭代,为True
loop.lenth:序列中的项目数

goods = ['可乐', '雪碧', '芬达', '北冰洋', '椰奶']


@app.route('/goods')
def show_goods():
    return render_template('goods.html', goods=goods)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>循环loop的使用</title>
</head>
<body>
<table>
  <tr>
    <th>序号</th>
    <th>名称</th>
  </tr>
  {% for good in goods %}
    {% if loop.last %}
      <tr>
        <td>{{loop.index}}</td>
        <td>{{good}}</td>
      </tr>
      <tr>
        <td colspan="2" align="right">商品种类:{{loop.length}}</td>
      </tr>
    {% else %}
      <tr>
        <td>{{loop.index}}</td>
        <td>{{good}}</td>
      </tr>

    {% endif %}
  {% endfor %}
</table>
</body>
</html>

在这里插入图片描述

类似于函数,只不过在模板中定义宏就是定义函数,调用宏
步骤:

  1. 定义:macro.html
    {% macro 宏名(参数) %}
    使用各种模板语法:for、if… + html标签
    {% endmacro %}

  2. 使用宏:
    导入宏文件:
    {% import ‘macro.html’ as ma %}

调用:
{{ ma.宏名(参数) }}

@app.route('/macro')
def show_macro():
    return render_template('index4.html', goods=goods)

macro.html

{% macro input(name, id, type='text') %}
  <input type="{{type}}" id="{{id}}" name="{{name}}">
{% endmacro %}

{% macro show_data(datas,clazz='a1') %}
    <ul class="{{clazz}}">
      {% for data in datas %}
        <li>{{data}}</li>
      {% endfor %}
    </ul>
{% endmacro %}

index4.html:

{% import 'marco.html' as ma %}


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>macro的使用</title>
    <style>
        .a1{
            list-style: none;
            color: hotpink;
        }
    </style>
</head>
<body>
<div>
    {{ma.input('username','username')}}
</div>
<div>
    {{ma.input('password','password',type='password')}}
</div>

{{ ma.show_data(goods)}}
</body>
</html>

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值