django-DIL template custom filter

  • custom filter
    • The DTL template language was born only for the convenience of displaying information, so it is a bit weak compared with programming languages, and sometimes it cannot meet our needs. So django provides an interface that allows developers to customize tags and filters.
    • First, you need to add a templatetags folder, the custom filter must be in a package (folder) named "templatetags" in the installed app. So there are two options:
      • One is to put it in other installed apps. This method is simple, but inconvenient to manage.
      • Create a separate app to store all your own defined filters. Recommended Use
    • ps: The templatetags folder name cannot be modified, this is fixed by django

1. Use the above-mentioned second method to create a public app utils ------ tool, and create a templatetags fixed name under the utils app

Create a py file under templatetags and write a filter

2.py file utils.templatetags.py

# coding=utf-8
from django import template

#Represents that the file is a custom tag name register fixed writing 
register = template.Library()

# Called in the html template {{ msg|myCut:'args' }} 
@register.filter # Filter decorator
 def myCut(value, args): #Write
     code according to requirements 
    return u ' Custom filter some characters return lowercase : %s ' % (value.replace(args, '' ).lower())

3.***You need to import the app utils in the settings file

INSTALLED_APPS = [
     ' django.contrib.admin ' ,
     ' django.contrib.auth ' ,
     ' django.contrib.contenttypes ' ,
     ' django.contrib.sessions ' ,
     ' django.contrib.messages ' ,
     ' django.contrib.staticfiles ' ,
     ' utils ' , #Create custom filters need to import the app 
]

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325815588&siteId=291194637