zoukankan      html  css  js  c++  java
  • Django- filter和simpletag,inclusion_tag的用法

    filter的用法:

    #先引入template
    from django import template
    #声明register,名字只能是register
    register = template.Library()
    
    #带名字的装饰器,调用的时候用起的名字 如dsb
    @register.filter(name='dsb')
    def add_sb(value, arg):
        return "{}_{}abc".format(value, arg)
    
    @register.filter
    def add_sb(value, arg):
        return "{}_{}_abc".format(value, arg)
    

    自定义simpletag和自定义inclusion_tag
    1. 在app下创建一个名叫templatetags的python包
    2. 在templatetags里建一个py文件

    simpletag的用法:

    和自定义filter类似,只不过接收更灵活的参数。

    定义注册simple tag

    @register.simple_tag
    def join_str(arg1, arg2, arg3,*args,**kwargs):
        print(args) #('tian', 'shan', 'tong', 'lao')
        print(kwargs) #{'key1': 'menglang', 'key2': 'menggu'}
    
        #{% load mytags %}
        # {% join_str 'xiaofeng' 'duanyu' 'xuzhu' 'tian' 'shan' 'tong' 'lao' key1='menglang' key2='menggu' %}
        return '_'.join([arg1, arg2, arg3])+'*'.join(args)  #xiaofeng_duanyu_xuzhutian*shan*tong*lao
    

    inclusion_tag的用法: 多用于返回html代码片段

    @register.inclusion_tag('pagination.html')
    def pagination(total, current):
        return {'total': range(1, total + 1), 'current': current}
    

      

  • 相关阅读:
    地图实现
    shiro有哪些组件
    MyBatis 与 Hibernate 有哪些不同?
    .#{}和${}的区别是什么?
    SpringMVC 流程
    怎么防止重复提交
    2019.4.17 映纷创意首页铺设练习
    2019.4.16 掌恒首页铺设练习
    2019.4.9 小作业 淘宝商品显示块
    2019.4.9 HTML+CSS写静态百度首页
  • 原文地址:https://www.cnblogs.com/duanhaoxin/p/9629767.html
Copyright © 2011-2022 走看看