More filters

When outputting variables, filters are also supported to perform primary filtering of data. The format is:


{{obj|filter__name:param}}

For example, when a variable has a value, it outputs the current value, and when there is no value, it outputs the default value:
usedefaultSet the default value:


{{ userName|default:"大侠匿名"}}

As long as it is empty, it will be considered as none. We can also usedefault_if_noneTo handle it


{{ userName|default_if_none:"大侠匿名"}}
{{ ""|default_if_none:"n/a" }}
{{ nil|default_if_none:"n/a" }}

get_digitYou can get the numbers in the variable. If you specify the value of get_digit, you can get the last number. like:


{{ 1234567890|get_digit:0 }}
{{ 1234567890|get_digit }}
{{ 1234567890|get_digit:2 }}
{{ 1234567890|get_digit:"4" }}
{{ 1234567890|get_digit:10 }}
{{ 1234567890|get_digit:15 }}

uselengthOutput length:


{{ value|length }}

If the value is ['a', 'b', 'c', 'd'], then the output is 4.

divisiblebyIt can be judged whether a variable can be divisible, such as:


{{ 21|divisibleby:3 }}
{{ 21|divisibleby:"3" }}
{{ 21|float|divisibleby:"3" }}
{{ 22|divisibleby:"3" }}
{{ 85|divisibleby:simple.number }}
{{ 84|divisibleby:simple.number }}

dateTime can be formatted:


{{ value|date:``"2006-01-02 15:04"}}

Note that this value must be of time.Time type, not a timestamp. If it is a timestamp, it will report an error. The timestamp either converts it to the time.Time type in the controller, or uses our custom template function:


{{stampToDate(nowStamp, "2006-01-02 15:04")}}

truncatechars,truncatewordsIf there are more string characters and words than specified characters, they will be truncated. The truncated string will end with a translateable sequence of ellipses ("..."):


{{ value|truncatechars:9}}
{{ value|truncatewords:9}}

Truncate except string truncationtruncatechars, also supports word truncationtruncatewords

truncatechars_html,truncatewords_htmlSimilar functionstruncatechars,truncatewords. But these two tags are used to intercept strings in html, and it will not destroy the html structure. One is to cut by characters, and the other is to cut by words. The truncated string will end with a translateable sequence of ellipses ("..."):


{{ "This is a long test which will be cutted after some chars."|truncatechars_html:25 }}
{{ "This is a long test which will be cutted after some words."|truncatewords_html:5|safe }}

upper,lowerSingle characters can be converted into case:


{{ value|upper}}
{{ value|lower}}

capfirstIt can realize the capitalization effect of the first letter of a sentence, such as:


{{ "hello there!"|capfirst }}

cutIt can implement the removal of specific characters in variables. like:


{{ 15|cut:"5" }}
{{ "Hello world"|cut: " " }}

addYou can add the content to be output. It's equivalent to the golang+, the numbers will be added and the output result will be output, and the strings will be spliced ​​together. like:


{{ 5|add:6 }}
{{ 5|add:nothing }}
{{ 5|add:"test" }}
{{ "hello "|add:"john doe" }}

addslashesA backslash will be added before the specified predefined characters. These characters are single quotes ('), double quotes ("), backslash (\) and NUL (NULL characters). For example:


{{ "plain' text"|addslashes }}
{{ "plain' text"|addslashes|safe }}

titleLabels can enable the first letter of each word in a sentence to be uppercase and the rest to be lowercase, which is used to format the output of the title. like:


{{ "hello there!"|title }}
{{ "HELLO THERE!"|title }}
{{ "HELLO tHERE!"|title }}

yesnoyesno is used to verify whether a variable is valid. It can define three results, and the three results are respectively used in English commas.,Separate, valid value, invalid value, and unknown type. If not defined, you can also leave it blank. like:


{{ archive.Status|yesno}}
{{ archive.Status|yesno:"validated,not validated,unknown validation status"}}

striptagsstriptags  Similar to PHP’s strip_tags function, it can strip HTML, XML and PHP tags from strings. This tag always strips HTML comments. like:


{{"<title>Hello World</title>"|striptags}}
{{"<title>Hello World</title>"|striptags|safe}}

removetagsTags can delete the specified html tag. like:


{{ "<strong><i>Hello!</i></strong>"|removetags:"i"|safe }}

pluralizeTags can determine whether a variable is a plural. like:


customer{{ 0|pluralize }}
customer{{ 1|pluralize }}
customer{{ 2|pluralize }}
cherr{{ 0|pluralize:"y,ies" }}
cherr{{ 1|pluralize:"y,ies" }}
cherr{{ 2|pluralize:"y,ies" }}
walrus{{ 0|pluralize:"es" }}
walrus{{ 1|pluralize:"es" }}
walrus{{ simple.number|pluralize:"es" }}

randomA value in the set can be output randomly. like:


<p>{{ intList|random }}</p>

first,lastCan be used to output the first character and the last character in the output variable. like:


{{ "Test"|first }}
{{ "Test"|last }}

urlencodeThe urlencode tag can encode the variable url percentile number. like:


{{ "/?category_id=1"|urlencode }}

linebreaksbr,linebreaksBoth labels can turn newlines in variable values ​​into<br/>, equivalent to PHPnl2brfunction. like:


{{ archive.Description|linebreaksbr }}
{{ archive.Description|linebreaks }}
{{ archive.Description|linebreaksbr|safe }}
{{ archive.Description|linebreaks|safe }}

length_islength_is can determine the length of the value of the variable. You can only judge strings, numbers are not possible. like:


{{ "hello"|length_is:5 }}

integer,floatLabels can convert the value of a variable into integers and floating-point numbers. like:


{{ "foobar"|integer }}
{{ "5.4"|float|integer }}
{{ "foobar"|float }}
{{ "5.5"|float }}
{{ "5.6"|integer|float }}

floatformatThe tag can keep the value of a variable in the floating point format, and only retain the decimal point by default. If the last bit is 0, the decimal point will not be retained. If the number of digits after the decimal point is specified, it is displayed as the number of digits. like:


{{ 34.23234|floatformat }}
{{ 34.00000|floatformat }}
{{ 34.23234|floatformat:3 }}
{{ 34.00000|floatformat:3 }}
{{ "34.23234"|floatformat }}
{{ "34.00000"|floatformat }}
{{ "34.23234"|floatformat:3 }}
{{ "34.00000"|floatformat:3 }}

joinAn array can be matched by a given separation and become a string. like:


{{intList|join:", "}}

splitJust in time andjoinInstead, it can convert a string into an array by the given separator. like:


{{ "Hello, 99, 3.140000, good"|split:", "|join:", " }}

stringformatYou can format numbers and strings into specified formats to output. Equivalent tofmt.Sprintf(). like:


{{ 0.55555|stringformat:"%.2f" }}
{{ 888|stringformat:"Test: %d" }}
{{ "你好"|stringformat:"Chinese: %s" }}

make_listYou can split a string into an array by character, which is equivalent to[]rune("你好啊"). like:


{{ "你好啊"|make_list|join:", " }}
{% for char in "你好啊"|make_list %}{{ char }},{% endfor %}

centerThis tag is more interesting. You can format the string to a specified length and place the string in the middle and fill it with spaces next to it. If the given length is less than the string length, no changes are made. like:


'{{ "test"|center:3 }}'
'{{ "test"|center:20 }}'
{{ "test"|center:20|length }}

ljust,rjustThese two tags andcenterAlmost all, the string is filled to the specified length, but the filling direction is different.ljustThe space will be filled on the right, that is, the string will be left.rjustThe space will be filled on the left, which means that the string will be right. like:


'{{ "test"|ljust:"20" }}'
{{ "test"|ljust:"20"|length }}
'{{ "test"|rjust:"20" }}'
{{ "test"|rjust:"20"|length }}

wordcountUsed to count the length of the string. It has two ways to use it, one is after the string, and the other is to use the filter tag. like:


{{ ""|wordcount }}
{% filter wordcount %}{% lorem 25 w %}{% endfilter %}

wordwrapA string can be wrapped by a given length. like:


{{ "hello world"|wordwrap:2 }}
<pre>{% filter wordwrap:5 %}{% lorem 26 w %}{% endfilter %}</pre>
{{ "Lorem ipsum dolor sit amet, consectetur adipisici elit."|wordwrap:2|linebreaksbr|safe }}

urlizeThe a tag will be automatically added to the url and mailbox, and the nofollow rel will be automatically added. This is more appropriate to deal with the main text of the article. urlize also supports setting true and false to indicate whether the displayed connection content is escaped. like:


<p>{{ ""|urlize|safe }}</p>
<p>{{ "www.kandaoni.com"|urlize|safe }}</p>
<p>{{ "kandaoni.com"|urlize|safe }}</p>
<p>{% filter urlize:true|safe %}</p>
<p>Please mail me at [email protected] or visit mit on:</p>
<p>- lorem ipsum http://www.kandaoni.com lorem ipsum</p>
<p>- lorem ipsum  lorem ipsum</p>
<p>- lorem ipsum  lorem ipsum</p>
<p>- lorem ipsum www.kandaoni.com lorem ipsum</p>
<p>- lorem ipsum www.kandaoni.com/test="test" lorem ipsum</p>
<p>{% endfilter %}</p>
<p>{% filter urlize:false|safe %}</p>
<p>- lorem ipsum www.kandaoni.com/test="test" lorem ipsum</p>
<p>{% endfilter %}</p>

urlizetruncThe role ofurlizeAlmost all, they automatically add a tag to the url and mailbox, but they can set the url content to display the part of the url content, and use it after the specified length....replace. like:


<p>{% filter urlizetrunc:15|safe %}</p>
<p>Please mail me at [email protected] or visit mit on:</p>
<p>- lorem ipsum http://www.kandaoni.com lorem ipsum</p>
<p>- lorem ipsum  lorem ipsum</p>
<p>- lorem ipsum  lorem ipsum</p>
<p>- lorem ipsum www.kandaoni.com lorem ipsum</p>
<p>- lorem ipsum www.kandaoni.com/test="test" lorem ipsum</p>
<p>{% endfilter %}</p>

escapejsThe string will be pressed\uxxxxEncode preset characters. like:


{{ "<p>aaa</p><script>alert('xss');</script><p>bbbb</p>"|escapejs|safe }}

sliceYou can intercept data of a specified length to strings and arrays. like:


{{ "Test"|slice:"1:" }}
{{ "Test"|slice:":3" }}
{{ "Test"|slice:"1:3"|join:"," }}
{{ intList|slice:"1:5"|join:"," }}

safeDjango's templates will automatically escape syntax tags such as HTML tags and JS, which is for security and prevent xss attacks.

If you don't want to use escape, usesafeTo declare that the content to be output is safe, it will not be automatically escaped, and it can also be usedautoescapeTags to control turning on and off automatic escape:


用safe关闭自动转义
{{ "<script>alert('xss');</script>"|safe}}
强制开启自动转义
{% autoescape on %}
{{ "<script>alert('xss');</script>" }}
{% endautoescape %}
强制关闭自动转义,相当于使用了safe
{% autoescape off %}
{{ "<script>alert('xss');</script>" }}
{% endautoescape %}

escapeescape can also perform declaration escape. Since it will be automatically escaped by default, if you use escape here, it will be escaped twice. Therefore useautoescape offAfter closing escape, using escape is equivalent to direct output. like:


{{ "<script>alert('xss');</script>" }}
相当于
{% autoescape off %}
{{ "<script>alert('xss');</script>"|escape }}
{% endautoescape %}

All filter tags above can be used{% filter 标签名 %}内容{% endfilter %}来使用。比如:


{% filter lower %}This is a nice test; let's see whether it works. Foobar. {{ simple.xss }}{% endfilter %}

{% filter truncatechars:10|lower|length %}This is a nice test; let's see whether it works. Foobar. {{ simple.number }}{% endfilter %}

<p>{% filter urlize:false|safe %}</p>
<p>- lorem ipsum www.kandaoni.com/test="test" lorem ipsum</p>
<p>{% endfilter %}</p>