django神器 <自定义过滤器filter 和 标签tag>

自定义过滤器filter和标签tag

  • filter 自定义过滤器

    • 创建

      1. 在app下创建一个名为templatetags的python包(名称不能变)

      2. 在templatetags 创建py文件 自定义名称 my_tags.py(名称自定义)

      3. 在py文件中写入:

        from django import template
        
        register = template.Library()  # register也不能变
      4. 写函数+装饰器

        @register.filter
        def add_xx(value, arg):  # 最多有两个
        
            return '{}-{}'.format(value, arg)
    • 使用
      1. 使用

        {% load my_tags %}
        {{ 'alex'|add_xx:'dsb' }}
  • simpletag 标签(返回内容自定义)

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

    • 定义注册simple tag

      @register.simple_tag(name="plus")
      def plus(a, b, c):
          return "{} + {} + {}".format(a, b, c)
    • 使用自定义simple tag

      {% load app01_demo %}
      
      {# simple tag #}
      {% plus "1" "2" "abc" %}
  • inclusion_tag 标签(函数内返回内容必须是一个字典,第三个文件去渲染,然后代码段返回给html文件)

    示例:

    1. templatetags/my_inclusion.py
    from django import template
    
    register = template.Library()
    
    
    @register.inclusion_tag('result.html')
    def show_results(n):
        n = 1 if n < 1 else int(n)
        data = ["第{}项".format(i) for i in range(1, n+1)]
        return {"data": data}
    1. templates/result.html
    <ul>
      {% for choice in data %}
        <li>{{ choice }}</li>
      {% endfor %}
    </ul>
    1. templates/index.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta http-equiv="x-ua-compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>inclusion_tag test</title>
    </head>
    <body>
    
    {% load my_inclusion %}
    
    {% show_results 10 %}
    </body>
    </html>

转载于:https://www.cnblogs.com/bigox/p/10700567.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值