Custom tag filter

. 1 2 stencil of the filter
 2          - Syntax: {{first parameter | filter Name: second parameter}}
 . 3          - Common filter :( detailed usage see source)
 . 4              - length
 . 5              - default
 . 6              - Slice
 . 7              - DATE
 . 8              - filesizeformat
 . 9              - truncatechars
 10              - truncatewords
 . 11              - Safe
 12 is              - the Add
 13 is      . 3 templates of tag
 14         - {% tag% }
 15          - for : magic forloop: Object (there are a lot of things: parentloop, last, first, counter ....) forget it, print it yourself
 16              empty: the cycle of the object is empty, just take it
 . 17              for loops can be nested, can also be used IF
 18 is          - IF :
 . 19              {% IF forloop.first% }
 20 is                  <P> my first </ P>
 21 is              {% elif forloop.last% }
 22 is                  <P> Finally, I </ P>
 23 is              {% the else % }
 24                  <P> {} {} foo </ P> bar
25              {% endif% }
 26 is          - with: rename, application of variable names
 27          ******** ******** should have ended
 28          
29      . 4 custom tags and filters
 30          - *** tag can not be used if the judge, the filter can be used in determining if
 31 is          - custom filter
 32              -1 to app is not registered in the setting
 33 is              -2 app created at a templatetags (** ** *** can not change the name of the file) folder (module)
 34              -3 create a py file in the module name at random: mytag.py
 35              -4 # the first step, import Template 
36                 from django.template import Library
37                 # Second, define a variable named register template.Library = () 
38 is                 register = Library ()
 39              -5 to write a function, with register.filter @ (name = ' yyy ' decorate) (can be aliased)
 40                  DEF str_add (str1, str2): # must have a return value 
41                      # business logic is complex 
42 is                      return str1 + str2
 43 is              -6 new definitions given label :( filter template, should restart the program)
 44 is                  - % Load% MyTag { }
 45                  - {{ ' LQZ ' | str_add: ' Nb ' }}
46 is          - custom label:
 47              -1-4 : before step 4, the filter is defined exactly as the root
 48              -5 but not the same decorator
 49              @ register.simple_tag ()
 50                  DEF add_nb (value):
 51 is                      return value + ' Nb ' 
52 is              -6 in the template :( more parameters separated by a space)
 53 is                  - {MyTag% Load% }
 54 is                  - {% add_nb ' XQD ' % }
 55             

Guess you like

Origin www.cnblogs.com/xuqidong/p/12099535.html