When outputting variables, it also supports using filters to perform primary data filtering, format is:
{{obj|filter__name:param}}
For example, a variable that outputs the current value when it has a value and the default value when it does not: usedefaultSet the default value:
{{ userName|default:"大侠匿名"}}
default If it is empty, it is considered to be none. We can also usedefault_if_noneto process
{{ userName|default_if_none:"大侠匿名"}}
{{ ""|default_if_none:"n/a" }}
{{ nil|default_if_none:"n/a" }}
get_digitCan retrieve numbers from variables, if the value of get_digit is specified, it can retrieve the number from the end. For example:
{{ 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 value is ['a', 'b', 'c', 'd'], the output is 4.
divisiblebyYou can determine whether a variable can be divided evenly, such as:
{{ 21|divisibleby:3 }}
{{ 21|divisibleby:"3" }}
{{ 21|float|divisibleby:"3" }}
{{ 22|divisibleby:"3" }}
{{ 85|divisibleby:simple.number }}
{{ 84|divisibleby:simple.number }}
dateCan format time:
{{ value|date:``"2006-01-02 15:04"}}
Pay attention, this value must be of type time.Time, not a timestamp, as it will report an error if it is a timestamp.Timestamp can either be converted to time.Time type in the controller or use our custom template function:
{{stampToDate(nowStamp, "2006-01-02 15:04")}}
truncatechars/truncatewordsIf a string character, word is more than the specified character count, it will be truncated. The truncated string will end with a translatable ellipsis sequence ("..."):
{{ value|truncatechars:9}}
{{ value|truncatewords:9}}
Truncate except string truncationtruncatecharsAlso supports truncation by wordtruncatewords
truncatechars_html/truncatewords_htmlSimilar functiontruncatechars/truncatewords. But these 2 tags are used to extract strings from html, they will not destroy the html structure.One is by character cutting, and the other is by word cutting. The truncated string will end with a translatable ellipsis sequence ("..."):
{{ "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/lowerCan convert the case of single characters:
{{ value|upper}}
{{ value|lower}}
capfirstCan achieve the effect of capitalizing the first letter of a sentence, such as:
{{ "hello there!"|capfirst }}
cutCan delete specific characters from a variable. For example:
{{ 15|cut:"5" }}
{{ "Hello world"|cut: " " }}
addCan append content to be output. Equivalent to golang's+, Numbers will be added together and the result will be output, strings will be concatenated together. For example:
{{ 5|add:6 }}
{{ 5|add:nothing }}
{{ 5|add:"test" }}
{{ "hello "|add:"john doe" }}
addslashesIt will add a backslash before the specified predefined characters. These characters are the single quote ('), double quote ("), backslash (\), and NUL (NULL character). For example:
{{ "plain' text"|addslashes }}
{{ "plain' text"|addslashes|safe }}
titleThe label can capitalize the first letter of each word in a sentence and make the rest lowercase, used for formatting title output. For example:
{{ "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 separated by English commas,Separate, valid values, invalid values, unknown type. If not defined, it can also be left blank. For example:
{{ archive.Status|yesno}}
{{ archive.Status|yesno:"validated,not validated,unknown validation status"}}
striptagsstriptags is similar to PHP's strip_tags function, which can strip HTML, XML, and PHP tags from a string.This tag always strips HTML comments. For example:
{{"<title>Hello World</title>"|striptags}}
{{"<title>Hello World</title>"|striptags|safe}}
removetagsTags can remove specified HTML tags. For example:
{{ "<strong><i>Hello!</i></strong>"|removetags:"i"|safe }}
pluralizeThe tag can determine if a variable is plural. For example:
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" }}
randomCan randomly output one value from a collection. For example:
<p>{{ intList|random }}</p>
first/lastCan be used to output the first and last characters of a variable. For example:
{{ "Test"|first }}
{{ "Test"|last }}
urlencodeThe urlencode tag can be used to perform URL percent encoding on variables. For example:
{{ "https://www.kandaoni.com/?category_id=1"|urlencode }}
linebreaksbr/linebreaksBoth tags can convert newline characters in the variable value to<br/>which is equivalent to PHP'snl2brfunction. For example:
{{ archive.Description|linebreaksbr }}
{{ archive.Description|linebreaks }}
{{ archive.Description|linebreaksbr|safe }}
{{ archive.Description|linebreaks|safe }}
length_islength_is can determine the length of a variable's value. It can only determine strings, not numbers. For example:
{{ "hello"|length_is:5 }}
integer/floatLabels can convert the value of a variable into an integer or a floating-point number. For example:
{{ "foobar"|integer }}
{{ "5.4"|float|integer }}
{{ "foobar"|float }}
{{ "5.5"|float }}
{{ "5.6"|integer|float }}
floatformatThe tag can keep the value of the variable in floating-point format with a specified decimal point, by default it only retains one decimal place, and if the last digit is 0, the decimal point is not retained.If a decimal place is specified, it will be displayed with the specified number of decimal places. For example:
{{ 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 }}
joinCan merge an array into a string using a given delimiter. For example:
{{intList|join:", "}}
splitJust andjoinOn the contrary, it can convert a string into an array using a given delimiter. For example:
{{ "Hello, 99, 3.140000, good"|split:", "|join:", " }}
stringformatIt can format numbers and strings into a specified format. Equivalent tofmt.Sprintf(). For example:
{{ 0.55555|stringformat:"%.2f" }}
{{ 888|stringformat:"Test: %d" }}
{{ "你好"|stringformat:"Chinese: %s" }}
make_listSplitting a string into an array of characters is equivalent to[]rune("你好啊"). For example:
{{ "你好啊"|make_list|join:", " }}
{% for char in "你好啊"|make_list %}{{ char }},{% endfor %}
centerThis label is quite interesting, it can format a string to a specified length and place the string in the middle, with spaces filled on the sides.If the given length is less than the string length, no change will be made. For example:
'{{ "test"|center:3 }}'
'{{ "test"|center:20 }}'
{{ "test"|center:20|length }}
ljust/rjustThese two tags andcenterThey are almost the same, both are used to pad a string to a specified length, but the padding direction is different.ljustThe space is filled on the right, which means the string is aligned to the left.rjustThe space is filled on the left, which means the string is aligned to the right. For example:
'{{ "test"|ljust:"20" }}'
{{ "test"|ljust:"20"|length }}
'{{ "test"|rjust:"20" }}'
{{ "test"|rjust:"20"|length }}
wordcountIt is used to calculate the length of a string. It has 2 usage methods, one is at the end of the string, and the other is using the filter tag. For example:
{{ ""|wordcount }}
{% filter wordcount %}{% lorem 25 w %}{% endfilter %}
wordwrapCan format a string by given length. For example:
{{ "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 }}
urlizeIt will automatically add an a tag to the url and email, and automatically add the nofollow rel.This is suitable for processing the main text of the article. urlize also supports setting true and false to indicate whether the displayed link content is escaped. For example:
<p>{{ "https://www.kandaoni.com"|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 https://www.kandaoni.com lorem ipsum</p>
<p>- lorem ipsum https://www.kandaoni.com 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>
urlizetruncand function ofurlizeMore or less, they are all automatically adding an a tag to the url and email, but it is possible to set a display section of the url content, using the specified length, and the rest...instead. For example:
<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 https://www.kandaoni.com lorem ipsum</p>
<p>- lorem ipsum https://www.kandaoni.com 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>
escapejsWill encode strings according to\uxxxxThe predefined characters. For example:
{{ "<p>aaa</p><script>alert('xss');</script><p>bbbb</p>"|escapejs|safe }}
sliceCan截取strings, arrays to the specified length data. For example:
{{ "Test"|slice:"1:" }}
{{ "Test"|slice:":3" }}
{{ "Test"|slice:"1:3"|join:"," }}
{{ intList|slice:"1:5"|join:"," }}
safeDjango's templates automatically escape HTML tags and JS syntax tags, which is for security reasons to prevent XSS attacks.
If you don't want to use escaping, you should usesafeto declare that the output content is safe, it will not be automatically escaped, and you can also useautoescapetags to control the opening and closing of automatic escaping:
用safe关闭自动转义
{{ "<script>alert('xss');</script>"|safe}}
强制开启自动转义
{% autoescape on %}
{{ "<script>alert('xss');</script>" }}
{% endautoescape %}
强制关闭自动转义,相当于使用了safe
{% autoescape off %}
{{ "<script>alert('xss');</script>" }}
{% endautoescape %}
escapeescape can also be used for declarative escaping. Since it is already automatically escaped by default, using escape here will result in double escaping. Therefore, useautoescape offAfter escaping, using escape equals direct output. For example:
{{ "<script>alert('xss');</script>" }}
相当于
{% autoescape off %}
{{ "<script>alert('xss');</script>"|escape }}
{% endautoescape %}
All the filter tags mentioned above can be used{% filter 标签名 %}内容{% endfilter %}to use. For example:
{% 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>