flask的jinja2过滤器使用:遍历索引指定标签class属性,实现样式变化

在flask项目中实现上图效果,采用使用自定义过滤器的形式对 span 标签的 class 指定。

1、定义过滤器

# common.py

def do_index_class(index):
    """自定义过滤器"""
    if index == 0:
        return "first"
    elif index == 1:
        return "second"
    elif index == 2:
        return "third"
    else:
        return ""

2、在 flask 项目 app 创建的函数里面注册过滤器

from info.utils.common import do_index_class
# 添加自定义过滤器
app.add_template_filter(do_index_class, "index_class")

3、 index.html 中使用自定义过滤器(loop.index0 | indexClass )

loop.index0:当前循环的索引
{% for news in data.click_news_list %}
    <li><span class="{{ loop.index0 | indexClass }}">{{ loop.index }}</span></li>
{% endfor %}

4、视图

@app.route('/')
def index():
    data = {
        "click_news_list": ['aaa', 'bbb','ccc'],
    }
    return render_template('./index.html', data=data)

5、css

.first{
    background: #f33;
    color:#fff;
}

.second{
    background:#ff722b;
    color:#fff;
}

.third{
    background:#fa3;
    color:#fff;

猜你喜欢

转载自www.cnblogs.com/mzfly/p/9999876.html