返回顶部

django神器 <自定义过滤器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>
posted @ 2019-04-13 12:11  高薪程序员  阅读(380)  评论(0编辑  收藏  举报