Django Primer: Template Filter

Source: Internet
Author: User
Tags datetime file size html tags join lowercase urlencode valid pprint

Reproduced
The original author basically writes the contents of the Django website to the translator, translating the address http://python.usyiyi.cn/django/ref/templates/builtins.html# Built-in-filter-reference Second, filter

1. The filter can be used to modify the display of the variable, the form of the filter is: {{variable | filter}}, pipe symbol ' | ' Represents the use
of filters 2. Filters can be used in a chained way, for example: {{text | escape | linebreaks}}
3. Filters can also take parameters, for example: {{bio|truncatewords:30}}
4. If there is a space in the parameter of the filter, enclose it in quotation marks, for example: {{list | join: ', '}}
5.django 30 built-in filters
(1) Add
        Use form: {{value | add: ' 2}}
        meaning: Increase value by 2
(2) addslashes
        Use form: {{value | addslashes}}
        meaning: Add backslash before quotation mark in value
(3) Capfirst
        Used in the form: {{value | capfirst}}
        meaning: The first character of value is converted to an uppercase form
(4) Cut
         Use the form: {{value | cut:arg}}, for example, if value is "String with spaces" Arg is "" then the output is "stringwithspaces"
         meaning: Remove all arg values from the given value
(5) Date
         The form of use is::
             (a) {{value | date: "D D M Y"}}, for example, if value is a DateTime object (Datetime.datetime.now ()) then the output will be the string "Wed-Jan" 
   (b) {{value | date}}, this form does not format the string, and the formatted string is automatically in the form set by Date_format.
         meaning: Output date format data in a given format
(6) Default
         Use form: {{value | default: ' Nothing '}}, for example, if value is "", then the output will be
         meaningless: if value is false, the output uses the default value
(7) Default_if_none
         Use form: {{value | default_if_none: ' Nothing '}}, for example, if value is none, then the output will be
         meaningless: if value is None, the output will use the default value
(8) Dictsort
         Meaning: If value is a dictionary, the return value is used as the result of the keyword sort
         : {{value | dictsort: ' Name '}}, for example,
         if value is:

[
{' name ': ' Zed ', ' age ': 19},
{' name ': ' Amy ', ' Age ': 22},
{' name ': ' Joe ', ' Age ': 31},
]
Then, the output is:
[
{' name ': ' Amy ', ' Age ': 22},
{' name ': ' Joe ', ' Age ': 31},
{' name ': ' Zed ', ' age ': 19},
] (9) dictsortreversed

Meaning: If value is a dictionary, then the return value is the inverse of the result ordered by the keyword
Use form: Exactly the same as above (8). (Ten) Divisibleby

Use form: {{value | divisibleby:arg}}, if value is 21,arg is 3, then the output will be true
Meaning: If value can be divisible by ARG, then the return value will be true (one) escape

Use form: {{value | escape}}
Meaning: Replace some of the characters in value to accommodate HTML formatting, including:
< is converted to &lt;
> is converted to &gt;
' (single quote) are converted to & #39;
"(double quote) is converted to &quot;
& is converted to &amp;

Escape only works in the output, so escape is not enough in the middle of a chain filter,
He should always be the last filter, if you want to use in the middle of the chain filter, then you can use Force_escape (Escapejs)

Use form: {{value | escapejs}}
Meaning: Replace some of the characters in value to accommodate JavaScript and JSON formats. (Filesizeformat)

Use form: {{value | filesizeformat}}
Meaning: Format value to make it an easy-to-read file size, for example: 13KB,4.1MB. (+) first

Use form: {{value | first}}
Meaning: Returns the first item in the list, for example, if value is a list [' A ', ' B ', ' C '], then the output will be ' a '. (Floatformat)

Use form: {{value | floatformat}} or {{Value|floatformat:arg}},
Arg can be a positive number or a negative number. Floatformat with no parameters is equivalent to Floatformat:-1
(1) If you do not have ARG, the engine rounds up and retains at most one decimal.

34.23234 {{Value|floatformat}} 34.2
34.00000 {{Value|floatformat}} 34
34.26000 {{Value|floatformat}} 34.3

(2) If ARG is a positive number, the engine rounds and retains the decimal of the ARG bit.

34.23234 {{Value|floatformat:3}} 34.232
34.00000 {{Value|floatformat:3}} 34.000
34.26000 {{Value|floatformat:3}} 34.260

(3) If ARG is a negative number, then the engine rounds and if there is a fractional part, the ARG bit is reserved, otherwise there is no fractional part.

34.23234 {{value|floatformat: '-3 '}} 34.232
34.00000 {{value|floatformat: '-3 '}} 34
34.26000 {{value|floatformat: "-3"}} 34.26 (+) Get_digit

Use form: {{value | get_digit: ' arg '}}, for example, if value is 123456789,arg is 2, then the output is 8
Meaning: Given a number, return, the number of requests, remember: 1 represents the rightmost number, if value is not a valid input,
Then all the original values are returned. (+) Iriencode

Use form: {{value | iriencode}}
Meaning: If the value has non-ASCII characters, then it is captured into the appropriate encoding in the URL, if value has been urlencode,
Operation will no longer work. () Join

Use form: {{value | join: ' ARG '}}, if value is [' A ', ' B ', ' C '],arg is '//' then the output is a//b//c
Meaning: Connect a list with the specified string, acting as Python's str.join (list) last

Use form: {{value | last}}
Meaning: Returns the last item in the list length

Use form: {{value | length}}
Meaning: Returns the length of the value. (length_is)

Use form: {{value | length_is: ' ARG '}}
Meaning: Returns True if the length of value equals arg, for example: if value is [' A ', ' B ', ' C '],arg is 3, then return true linebreaks

Use form: {{Value|linebreaks}}
Meaning: "\ n" in value will be replaced by <br/>, and the entire value is surrounded by </p>, thus in the format of HTML (LINEBREAKSBR)

Use form: {{value |LINEBREAKSBR}}
Meaning: "\ n" in value will be replaced by <br/> (linenumbers)

Use form: {{value | linenumbers}}
Meaning: The displayed text, with the number of lines. (+) Ljust

Use form: {{value | ljust}}
Meaning: In a field of a given width, align left to display value Center

Use form: {{value | center}}
Meaning: In a field of a given width, center alignment displays value (rjust)

Use form: {{value | rjust}}
Meaning: In a field of a given width, right-aligned display value (lower)

Use form: {{value | lower}}
Meaning: Convert a string to lowercase (make_list)

Use form: {{value | make_list}}
Meaning: Converts value to a list, to a string, to a character list, and to an integer, to an integer list
For example, if value is Joel, then the output will be [u ' J ', u ' o ', U ' e ', U ' l '];value is 123, then the output will be [all-in-one] (+) pluralize

Usage form: {{value | pluralize}}, or {{value | pluralize: ' ES '}}, or {{value | pluralize: ' y,ies '}}
Meaning: If value is not 1, then a plural suffix is returned, and the default suffix is ' s ' (+) Random

Use form: {{value | random}}
Meaning: Returns an arbitrary item (Removetags) from the given list

Use form: {{value | removetags: "TAG1 tag2 tag3 ..."}}
Meaning: Remove the label of Tag1,tag2 ... in value. For example, if value is <b>Joel</b> <button>is</button> a <span>slug</span>
tags is "b span", then the output will be: Joel <button>is</button> a slug (safe)

Use form: {{value | safe}}
Meaning: When the system setup autoescaping is turned on, the filter makes the output non-escape conversion (SAFESEQ)

This is basically the same as safe, but one thing is different: safe is for strings, and SAFESEQ is a sequence for multiple strings slice

Use form: {{some_list | slice: ': 2 '}}
Meaning: Same as slice in Python syntax: 2 represents the second element of the first (slugify)

Use form: {{value | slugify}}
Meaning: Convert value to lowercase, colleagues delete all sub-word characters, and turn spaces into horizontal lines
For example: If value is a slug of Joel is a, then the output will be Joel-is-a-slug (PNS) StringFormat

It's not used very often, but not first.
{{value|stringformat: "E"}}
If value is, the output would be 1.000000E+01. (striptags)

Use form: {{value | striptags}}
Meaning: Delete all HTML tags in value (all) time

Usage form: {{value | time: ' H:I '}} or {{value | time}}
Meaning: Format the time output, and if there are no formatting parameters behind it, then the output is set in Time_format. (+) title

Converts a string into the title format. (truncatewords)

Use form: {{value | truncatewords:2}}
Meaning: Cut the value into truncatewords the specified number of words
For example, if value is the Joel is a slug then the output will be: Joel is ... (truncatewords_html)

Use form same as (41)
Meaning: If a label is open before truncation, but does not close, then the truncation point will be closed immediately.
Because this operation is less efficient than truncatewords, it is only considered when value is in HTML format. (Upper)

Convert a string to uppercase (UrlEncode)

UrlEncode a String (urlize)

Meaning: Converts a URL in a string into a clickable form.
Use form: {{value | urlize}}
For example, if value is a check out www.djangoproject.com, then the output will be:
Check out <a href= "http://www.djangoproject.com" >www.djangoproject.com</a> (Urlizetrunc)

Use form: {{value | urlizetrunc:15}}
Meaning: Same as (45), but a little different is that the actual link character will be truncate to a specific length, followed by ... Reality. (WordCount)

Returns the number of words in a string (WordWrap)

Use form: {{value | wordwrap:5}}
Meaning: Wraps the string according to the specified length
For example, if value is a slug of Joel is a, then the output will be:
Joel
is a
Slug (timesince)

Use form: {{value |
Since:arg}}
Meaning: Returns the number of days and hours of the parameter arg to value
For example, if Blog_date is a date instance that represents 2006-06-01 midnight, and Comment_date is a date instance representing the 2006-06-01 morning of 8 points,
Then {{Comment_date|timesince:blog_date}} will return "8 hours". (Timeuntil)

Use form: {{value | timeuntil}}
Meaning: Similar to (50), a different point is that the value returned is the number of days and hours from the current date.

The following is not mentioned by the original author, found in the original (Wuyi) phone2numeric

Converts a phone number (possibly containing letters) to its numerical Equivalen
The input doesn ' t has to be a valid phone number. This would happily convert any string.
For example:
{{Value|phone2numeric}}
If value is 800-collect, the output would be 800-2655328. (Pprint)

A wrapper around Pprint.pprint () –for debugging, really. (truncatechars_html¶)

New in Django 1.7.

Similar to Truncatechars, except the It is aware of HTML tags. Any tags that is opened in the string and is closed before the truncation point is closed immediately after the Truncat Ion.
For example:
{{Value|truncatechars_html:9}}
If value is ' <p>joel is a slug</p> ', the output would be ' <p>joel i...</p> '.
Newlines in the HTML content would be preserved. (unordered_list)

Receives a nested list that returns a list of HTML--<ul> tags that do not contain the start and end.

The list is assumed to have a valid format. For example, if Var contains [' States ', [' Kansas ', [' Lawrence ', ' Topeka '], ' Illinois '], then {{var|unordered_list}} will return:

<li>states
<ul>
        <li>kansas
        <ul>
                <li>Lawrence</li>
                < li>topeka</li>
        </ul>
        </li>
        <li>Illinois</li>
</ul>
</li>

Deprecated since version 1.8:an older, more restrictive and verbose input format is also supported: [' states ', [[' Kansas ' , [[' Lawrence ', []], [' Topeka ', []]], [' Illinois ', []]]. This syntax will no longer be supported in Django 2.0. (yesno¶)

Maps values for True, False, and (optionally) None, to the strings "yes", "no", "maybe", or a custom mapping passed as a C omma-separated list, and returns one of the those strings according to the value:

For example:

{{value|yesno: ' Yeah,no,maybe '}}

Value Argument Outputs
True Yes
True "Yeah,no,maybe" Yeah
False "Yeah,no,maybe" no
None "Yeah,no,maybe" maybe
None "Yeah,no" No (converts None to False if no mapping for None are given)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.