Custom filter templates django

  Since the filter definition templates must be placed in the app, and the app must be installed in INSTALLED_APPS. Then create a python package called templatetags (the name is fixed and can not be altered) in this app below. Then create a python file in this package below. Then write filter in this file.
  Filter is actually a function in python, but this function is registered to the template gallery, use this function later in the template. But there is a limit and the parameter, the first value of this parameter must be a filter in need of treatment, the second parameter is optional, and if so, then the template parameter passing. And the function of the filter can have up to two arguments. After writing the filter, then use register into django.template.library object. Example code is as follows:
the filter file:

. 1  from Django Import Template
 2  
. 3 Register = template.Library ()
 . 4  
. 5  DEF my_template (value)
 . 6  IF value =! '' :
 . 7 value + = ' % ' 
. 8  return value
 . 9  # Register filter 
10  # a first embodiment 
11 register.filter ( " my_template " , my_template) # quotes is the name when used in the template, the latter is a function name filter file. 
12  # The second way 
13Use @ register.filter decorator to decorate a filter function, default filter function name is the name of the template used, if modified using the name, just the name written on the parameters decorator can, such as @ register.filter ( ' My ' ), when used to write my, rather than my_template.

Template files required to load:

1 { # in the first line load filter} # 
2 {% Load " filter name file ' %}

Guess you like

Origin www.cnblogs.com/xshan/p/12129946.html