django - filter template

django- template filter

The role of the filter

  • Django back to return to the data template, for processing

Filter syntax

Value | Filter: Parameters

Common filter templates, built-in filter defaultfilters.pycan be viewed

  • date
    • date : 'Y-m-d H:i:s'
  • length: get the length
  • length_is: Analyzing length
  • random: returns a random element, a filtered list of tuples or
  • default: Set Default
  • filesizeformat: Format File Size

Custom filters (focus)

  • In one project 应用under a new templatetagspackage
  • In templatetagscase a new packetextra_filter.py
  • In extra_filter.pycustomize your own filters
from django.template.library import Library
register = Library()

@register.filter(is_safe=True)
def ext(value, arg=None):
   exts = ["doc", "docx", "exe", "pdf", "ppt", "rar", "txt", "xlsx", "zip"]
   return value if value in exts else "unknow"
  • In the settings.pyactivationtemplatetags
    INSTALLED_APPS = [
        ....
        'resource.templatetags',
    ]
  • In the template page using filters, add loadlabel
    {% load extra_filter %}
  • Matching is completed, the normal use of a custom filter

Guess you like

Origin www.cnblogs.com/leomessi10/p/11871714.html