在 app01 下新建一个 templatetags 的文件夹,然后创建 myfilter.py 文件

这个 templatetags 名字是固定的,myfilter 是自己起的

Python - Django - 模板语言之自定义过滤器

myfilter.py:

from django import template
register = template.Library()


@register.filter(name="sleep")  # name 是 html 中的过滤器名
def sleep(arg):
    return "%s is sleep" %arg

views.py:

from django.shortcuts import render, redirect, HttpResponse
from app01 import models


# Filter 测试
def filter_test(request):
    name = "Jack"
    return render(request, "filter_test.html", {"name": name})

filter_test.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Filter 测试</title>
</head>
<body>

<!-- 这里需要导入自定义的 filter --> {% load myfilter %} {{ name|sleep }} </body> </html>

 运行结果:

Python - Django - 模板语言之自定义过滤器

定义含参数的 filter:

myfilter.py:

from django import template
register = template.Library()


@register.filter(name="sleep")
def sleep(arg):
    return "%s is sleep" %arg


@register.filter(name="eat")
def eat(arg, arg1):
    return "%s is eating %s" %(arg, arg1)

filter_test.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Filter 测试</title>
</head>
<body>

{% load myfilter %}
{{ name|sleep }}
<br>
{{ name|eat:"meat" }}

</body>
</html>

运行结果:

Python - Django - 模板语言之自定义过滤器