flask中自定义过滤器的实例

demo:新闻点击排行榜前三的样式分别不同,前三之后的又是另外一个样式,怎样通过装饰器实现?

1.在工具类common.py文件中自定义过滤器:

# 1.定义函数
def do_index_class(index):
    if index==1:
        return 'first'
    elif index==2:
        return 'second'
    elif index==3:
        return 'third'
    else:
        return ''

2.在__init__.py文件中注册自定义过滤器

# 注册过滤器
    from info.utils.common import do_index_class
    # add_template_filter:第一个参数是函数名,第二个参数是自定义过滤器名称
    app.add_template_filter(do_index_class, 'index_class')

3.使用自定义过滤器:在index.html文件中使用自定义过滤器

loop.index:下标

index_class:下标对应的class值


<ul class="rank_list">
   {% for news in clickList1 %}
   	<li><span class="{{ loop.index | index_class }}">{{ loop.index }}</span><a href="/news/detail?id={{ news.id }}">{{ news.title }}</a></li>
   {% endfor %}
</ul>

猜你喜欢

转载自blog.csdn.net/longting_/article/details/80795554