Foreword
django templates have a lot of built-in filter to meet the needs of some common, if some built-in filter can not meet the demand, then we need to write some of the filters.
Custom filter
First create a templatetags in the app directory, attention must be templatetags directory, Biexia named said last unsuccessful!
Myfilter.py then create a new file, the file can be named a.
First ensure that your app is already registered in setting.py inside over
# Application definition
INSTALLED_APPS = [
'django.contrib.admin', # 内置后台管理系统
'django.contrib.auth', # 内置用户认证系统
'django.contrib.contenttypes', # django的ORM框架
'django.contrib.sessions', # session会话功能
'django.contrib.messages', # 消息提示功能
'django.contrib.staticfiles', # 查找静态资源路径
'yoyo', # 你自己的app应用
]
Writing Filters
In myfilter.py write your own definition file in the following format filter name, name = "replace", replace this is your own definition of the filter.
The following function is the function of the replacement value specified arg characters ~
from django import template
register = template.Library()
@register.filter(name='replace')
def myreplace(value, arg):
return value.replace(arg, '~')
Template references
When referring to the custom of the filter in the template, you must first load to load their own definition of the filter file
{% load myfilter %}
{{Hello | replace:} "!"} Is the function which corresponds to the character string hello! Replaced ~
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="referrer" content="no-referrer" />
<title>Title</title>
</head>
<body>
{% load myfilter %}
<div>
<p><span>hello:</span>{{ hello | replace:"!" }}</p>
</div>
</body>
</html>