Django template language -Filters (filter)

The Filters (filter)

In Django template language by using filters to change the display of variables.

The syntax of the filter: {{value | FILTER_NAME : Parameter}}

Use pipe symbol "|" applying a filter.

For example: {{name | lower}} then the variable name will show its value after the application of lower filter. lower in action here is all lowercase text.

Precautions:

  1. Filter supports the "chain" operation. I.e., a filter output as input to another filter.
  2. Filters can accept parameters, for example: {{sss | truncatewords: 30}}, which will display the first 30 words of sss.
  3. Filter parameter contains a space, it must be wrapped in quotes. Such as comma and a space used to connect the elements of a list, such as: {{list | join: ','}}
  4. '|' Around is no space without a space with no spaces

 

Django template language provides about sixty built-in filter.


 

  1. default

    # If a variable is false or empty, use given default. Otherwise, use the value of the variable. 
    
    Value {{ | default: " nothing " }} 
    
    # If value is null or the value is not passed, then nothing is displayed

     

  2. length

    # Returns the length, acting on the string and the value list. 
    
    Value {{ | length}} 
    
    # Returns the value of the length, such as the value = [ 'a', ' b', 'c', 'd'] , then, 4 is displayed.

     

  3. filesizeformat

    # The value formatted as a "human readable" file size (e.g. '13 KB ',' 4.1 MB ' ,' 102 bytes', etc.). For example: 
    
    {{value | filesizeformat}} 
    
    # if the value is 123456789, the output will be 117.7 MB.

     

  4. slice

    # Slice, with a list of similar operations. Package does not include front 
    
    {{value | Slice: " 2: -1 " }}

     

  5. date

    # Datetime type, time format 
    
    {{value | DATE: " Ymd H: I: S " }}

    Available parameters:

    Formatting characters description Sample output
    a 'a.m.'Or 'p.m.'(Note that this is slightly different with PHP's output, because this includes the period in line with Associated Press style) 'a.m.'
    A 'AM'Or 'PM'. 'AM'
    b Month, word, three letters, lowercase. 'jan'
    B Unrealized.  
    c ISO 8601 format. (Note: Unlike other formatting procedures, for example, "Z", "O" or "r", if the value naive datetime, the "c" format program does not add time zone offset (see datetime.tzinfo). 2008-01-02T10:30:00.000123+02:00Or 2008-01-02T10:30:00.000123if naive datetime
    d May the day with 2 digits with leading zeros. '01'To'31'
    D Word of the week, three letters. “星期五”
    e Time zone name may be in any format, or may return a null string, depending datetime. '', 'GMT', '-500', 'US/Eastern'Etc.
    E Month, instead of specific regions commonly used to represent long date representation. 'listopada'(For Polish regions, not 'Listopad')
    f Time, within 12 hours hours and minutes, if they are zero, the minute hold. Proprietary extensions. '1''1:30'
    F Month, text, long. '一月'
    g Hour, 12-hour format, without leading zeros. '1'To'12'
    G Hour, 24-hour format, without leading zeros. '0'To'23'
    h Hour, 12-hour format. '01'To'12'
    H Hour, 24-hour format. '00'To'23'
    i minute. '00'To'59'
    I Daylight Saving Time, regardless of whether or not to take effect. '1'or'0'
    j No day leading zeros of the month. '1'To'31'
    l Day of the week, word length. '星期五'
    L Whether the Boolean value is a leap year. TrueorFalse
    m Month, 2 digits with leading zeros. '01'To'12'
    M Month, word, three letters. “扬”
    n Months No leading zeros. '1'To'12'
    N Associated Press style abbreviation for the month. Proprietary extensions. 'Jan.''Feb.''March''May'
    O ISO-8601 week number corresponding to the number of weeks using the leap (W) ISO-8601. For the more common year format, see Y. '1999年'
    O Greenwich Mean Time difference within a few hours. '+0200'
    P For 12 hours, minutes and 'am. '/' pm. ', If the zero minute hold, in special circumstances the string "midnight" and the "noon." Proprietary extensions. '1 am''1:30 pm' / t3>,'midnight''noon''12:30 pm' / T10>
    r RFC 5322格式化日期。 'Thu, 21 Dec 2000 16:01:07 +0200'
    s 秒,带前导零的2位数字。 '00''59'
    S 一个月的英文序数后缀,2个字符。 'st''nd''rd''th'
    t 给定月份的天数。 28 to 31
    T 本机的时区。 'EST''MDT'
    u 微秒。 000000 to 999999
    U 自Unix Epoch以来的二分之一(1970年1月1日00:00:00 UTC)。  
    w 星期几,数字无前导零。 '0'(星期日)至'6'(星期六)
    W ISO-8601周数,周数从星期一开始。 153
    y 年份,2位数字。 '99'
    Y 年,4位数。 '1999年'
    z 一年中的日子 0365
    Z 时区偏移量,单位为秒。 UTC以西时区的偏移量总是为负数,对于UTC以东时,它们总是为正。 -4320043200

     

  6. safe

    #Django的模板中会对HTML标签和JS等语法标签进行自动转义,原因显而易见,这样是为了安全。但是有的时候我们可能不希望这些HTML元素被转义,比如我们做一个内容管理系统,后台添加的文章中是经过修饰的,这些修饰可能是通过一个类似于FCKeditor编辑加注了HTML修饰符的文本,如果自动转义的话显示的就是保护HTML标签的源文件。为了在Django中关闭HTML的自动转义有两种方式,如果是一个单独的变量我们可以通过过滤器“|safe”的方式告诉Django这段代码是安全的不必转义。
    
    #比如:
    
    value = "<a href='#'>点我</a>"
    
    {{ value|safe}}

     

  7. truncatechars

    # 如果字符串字符多于指定的字符数量,那么会被截断。截断的字符串将以可翻译的省略号序列(“...”)结尾。
    
    # 参数:截断的字符数
    
    {{ value|truncatechars:9}}
    
    # 注意:...占三个字符,如果传入9,那么最后显示6个字符+...

     

  8. truncatewords

    # 在一定数量的字后截断字符串。
    
    {{ value|truncatewords:9}}
    
    # 注意:这个函数,是专门为英语文章准备的。根据空格分割字符串,来判断字符数量。

     

  9. cut

    # 移除value中所有的与给出的变量相同的字符串
    
    {{ value|cut:' ' }}
    
    # 如果value为'i love you',那么将输出'iloveyou'.

     

  10. join

    # 跟Python的''.join(list)类似
    
    lst = ['a','b','c','d']
    
    {{ lst|join:' - ' }}
    
    a - b - c - d

     

  11. timesince

    # 将日期格式设为自该日期起的时间(例如,“4天,6小时”)。
    
    # 采用一个可选参数,它是一个包含用作比较点的日期的变量(不带参数,比较点为现在)。 例如,如果blog_date是表示2006年6月1日午夜的日期实例,并且comment_date是2006年6月1日08:00的日期实例,则以下将返回“8小时”:
    
    {{ blog_date|timesince:comment_date }}
    
    # 分钟是所使用的最小单位,对于相对于比较点的未来的任何日期,将返回“0分钟”。
    
    
    # 用于判断,传入的时间,是在当前时间的几分钟前

     

  12. timeuntil

    # 似于timesince,除了它测量从现在开始直到给定日期或日期时间的时间。 例如,如果今天是2006年6月1日,而conference_date是保留2006年6月29日的日期实例,则{{ conference_date | timeuntil }}将返回“4周”。
    
    # 使用可选参数,它是一个包含用作比较点的日期(而不是现在)的变量。 如果from_date包含2006年6月22日,则以下内容将返回“1周”:
    
    {{ conference_date|timeuntil:from_date }}
    
    
    # 用于判断传入时间,是当前时间的几分钟后

     

  13. 自定义filter

    自定义过滤器只是带有一个或两个参数的Python函数:

    • 变量(输入)的值 - -不一定是一个字符串
    • 参数的值 - 这可以有一个默认值,或完全省略

    例如,在过滤器{{var | foo:'bar'}}中,过滤器foo将传递变量var和参数“bar”

     

    自定义filter代码文件摆放位置:

    app01/
        __init__.py
        models.py
        templatetags/  # 在app01下面新建一个package package
            __init__.py
            app01_filters.py  # 建一个存放自定义filter的文件
        views.py

    编写自定义filter

    from django import template
    register = template.Library()
    
    
    @register.filter(name="cut")
    def cut(value, arg):
        return value.replace(arg, "")
    
    
    @register.filter(name="addSB")
    def add_sb(value):
        return "{} SB".format(value)

    使用自定义filter

    { # First import our custom filter that file} # 
    {% the Load app01_filters% } 
    
    { # Use our custom #} filter 
    {{someVariable | Cut: " 0 " }} 
    {{d.name | addSB}}

     

Guess you like

Origin www.cnblogs.com/wtil/p/11487944.html