Built-in Django filters
Django filters are designed to
format template variables. The syntax to apply Django filters is
the vertical bar character |
also known as 'pipe' in
Unix environments (e.g.{{variable|filter}}
). It's
worth mentioning that it's possible to use multiple filters on the
same variable (e.g.{{variable|filter|filter}}
).
I'll classify each built-in Django filter into functional sections so it's easier to identify them. The functional classes I'll use are: Dates, Strings, Lists, Numbers, Dictionaries, Spacing and special characters, Development and Testing & Urls.
Tip You can apply Django filters to entire sections with the {% filter %} tag. If you have a group of variables in the same section and want to apply the same filter to all of them, it's easier to use the {% filter %} tag than to individually declare the filter on each variable. The next section in this chapter on Django built-in tags provides more details on the {% filter %} tag
Dates
date
.- Thedate
filter formats Pythondatetime
objects and only works if the variable is this type of Python object. Thedate
filter uses a string to specify a format. For example, if a variable contains adatetime
object with the date 01/01/2022, the filter statement{{variable|date:"F jS o"}}
outputs January 1st 2022. The string syntax for the date filter is based on the characters described in table 3-3.
Tip If you provide no string argument to the date filter (e.g. {{variable|date}}), it defaults to the "N j, Y" string which comes from the default value of DATE_FORMAT.
Note The date filter can also accept predefined date variables {{variable|date:"DATE_FORMAT"}}, {{variable|date:"DATETIME_FORMAT"}}, {{variable|date:"SHORT_DATE_FORMAT" %} or {{variable|date:"SHORT_DATETIME_FORMAT"}}.
The predefined date variables in themselves are also composed of date strings based on the syntax in table 3-3. For example DATE_FORMAT default's to "N j, Y" (e.g. Jan 1, 2022), DATETIME_FORMAT defaults to "N j, Y, P" (e.g. Jan 1, 2022, 12 a.m.), SHORT_DATE_FORMAT defaults to "m/d/Y" (e.g. 01/01/2022) and SHORT_DATETIME_FORMAT defaults to "m/d/Y P" (e.g. 01/01/2022 12 a.m.). Each date variable can be overridden with different date strings in a project's settings.py file.
Table 3-3. Django date & time format characters
Standards based characters | Description |
---|---|
c | Outputs ISO 8601 format (e.g. 2022-01-02T10:30:00.000123+02:00 or 2022-01-02T10:30:00.000123 if the datetime has no timezone [i.e.naive datetime]) |
r | Outputs RFC 2822 formatted date (e.g.'Thu, 21 Dec 2022 16:01:07 +0200') |
U | Outputs seconds since Unix epoch date--January 1 1970 00:00:00 UTC |
I (Uppercase i) | Outputs whether daylight savings time is in effect (e.g.'1' or '0') |
Hour based characters | Description |
a | Outputs 'a.m.' or 'p.m.' |
A | Outputs 'AM' or 'PM' |
f | Outputs time, 12-hour hours and minutes, with minutes left off if they're zero (e.g.'1', '1:30') |
g | Outputs hour, 12-hour format without leading zeros (e.g.'1' to '12') |
G | Outputs hour, 24-hour format without leading zeros (e.g.'0' to '23') |
h | Outputs hour, 12-hour format (e.g.'01' to '12') |
H | Outputs hour, 24-hour format (e.g.'00' to '23') |
i | Outputs minutes (e.g.'00' to '59') |
P | Outputs time, 12-hour hours, minutes and 'a.m.'/'p.m.', with minutes left off if they're zero and the special-case strings 'midnight' and 'noon' if appropriate (e.g.'1 a.m.', '1:30 p.m.', 'midnight', 'noon', '12:30 p.m.') |
s | Outputs seconds, 2 digits with leading zeros (e.g.'00' to '59') |
u | Outputs microseconds (e.g.000000 to 999999) |
Timezone characters | Description |
e | Outputs timezone name. Can be in any format, or might return an empty string, depending datetime definition (e.g. '', 'GMT', '-500', 'US/Eastern') |
O | Outputs difference in timezone to Greenwich time in hours (e.g.'+0200') |
T | Outputs datetime time zone (e.g.'EST', 'MDT') |
Z | Outputs time zone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive (e.g.-43200 to 43200) |
Day and week characters | Description |
D | Outputs day of the week, textual, 3 letters (e.g.'Thu','Fri') |
l (Lowercase L) | Outputs day of the week, textual, long (e.g.'Thursday','Friday') |
S | Outputs English ordinal suffix for day of the month, 2 characters (e.g.'st', 'nd', 'rd' or 'th') |
w | Outputs day of the week, digits without leading zeros (e.g.'0' for Sunday to '6' for Saturday) |
z | Outputs day of the year (e.g.0 to 365) |
W | Outputs the week number of the year, with weeks starting on Monday based on ISO-8601 (e.g.1, 53) |
o | Outputs week-numbering year, corresponding to the ISO-8601 week number (W)(e.g.'1999') |
Month characters | Description |
b | Outputs textual month, 3 letters, lowercase (e.g.'jan','feb') |
d | Outputs day of the month, 2 digits with leading zeros (e.g.'01' to '31') |
j | Outputs day of the month without leading zeros (e.g. '1' to '31') |
E | Outputs month, locale specific alternative representation usually used for long date representation (e.g. 'listopada' for Polish locale, as opposed to 'Listopad') |
F | Outputs month, textual, long (e.g. 'January','February') |
m | Outputs month, 2 digits with leading zeros (e.g.'01' to '12') |
M | Outputs month, textual, 3 letters (e.g.'Jan','Feb') |
n | Outputs month without leading zeros (e.g.'1' to '12') |
N | Outputs month abbreviation in Associated Press style (e.g.'Jan', 'Feb', 'March', 'May') |
t | Outputs number of days in the given month (e.g. 28 to 31) |
Year characters | Description |
L | Outputs boolean for whether it's a leap year (e.g.True or False) |
y | Outputs year, 2 digits (e.g.'99') |
Y | Outputs year, 4 digits (e.g.'1999') |
To literally output a date character in a string statement you
can use the backslash character (e.g. {{variable|date:"jS
\o\f F o"}}
outputs 1st of January 2022, note the escaped
\o\f)
time
.- Thetime
filter formats the time component of a Pythondatetime
object. Thetime
filter is similar to thedate
filter which uses a string to specify a time format. For example, if a variable contains adatetime
object with a time of noon the filter statement{{variable|time:"g:i"}}
outputs 12:00. The time filter uses the same format characters illustrated in table 3-3 related to the time of day.
Tip If you provide no string argument to the date filter (e.g. {{variable|time}}), it defaults to the "P" string which comes from the default value of TIME_FORMAT.Note The time filter can also accept predefined a time variable {{variable|date:"TIME FORMAT"}.The predefined time is also composed of a time string based on the syntax in table 3-3. For example, TIME_FORMAT default's to "P" (e.g. 4 a.m.) and this can be overridden defining TIME_FORMAT in a project's settings.py file.
timesince
.- Thetimesince
filter outputs the time that's passed between adatetime
object and the current time. Thetimesince
filter output is expressed in seconds, minutes, hours, days or weeks. For example, if a variable contains thedatetime
object 01/01/2022 12:00pm and the current time is 01/01/2022 3:30pm the statement{{variable|timesince}}
outputs 3 hours 30 minutes. Thetimesince
filter can also calculate the time that's passed between twodatetime
object variables -- instead of the default current time -- by appending a second datetime object argument (e.g.{{variable|timesince:othervariable}}
).timeuntil
.-Thetimeuntil
filter outputs the time that needs to elapse from the current time to adatetime
object. Thetimeuntil
filter output is expressed in seconds, minutes, hours, days or weeks. For example, if a variable contains thedatetime
object 01/01/2022 10:00pm and the current time is 01/01/2022 9:00pm the statement{{variable|timeuntil}}
outputs 1 hour. Thetimeuntil
filter can also calculate the time that needs to elapse between twodatetime
object variables -- instead of the default current time -- by appending a seconddatetime
object argument (e.g.{{variable|timeuntil:othervariable}}
).
Strings, lists and numbers
add
.- Theadd
filter adds values. Theadd
filter can add two variables or a hardcoded value and a variable. For example, if a variable contains 5 the filter statement{{variable|add:"3"}}
outputs 8. If values can be coerced to integers -- like the last example -- theadd
filter performs a sum, if not the add filter concatenates. For a string variable that contains "Hello" the filter statement{{variable|add:" World"}}
outputs Hello World. For a list variable that contains ['a','e','i'] and another list variable that contains ['o','u'] the filter statement{{variable|add:othervariable}}
outputs ['a','e','i','o','u'].default
.- Thedefault
filter is used to specify a default value if a variable is false, doesn't exist or is empty. For example, if a variable doesn't exist in a template, contains False or is an empty string ('') the filter statement{{variable|default:"no value"}}
outputsno value
.default_if_none
.- The default filter is used to specify a default value if a variable isNone
. For example, if a variable containsNone
the filter statement{{variable|default_if_none:"No value"}}
outputsNo value
. Note if a variable contains an empty string (''
) this is not consideredNone
and thedefault_if_none
filter does not output its argument value.length
.- Thelength
filter is used to obtain the length of a value. For example, if a variable contains the stringlatte
the filter statement{{variable|length}}
outputs 5. For a list variable that contains['a','e','i']
the filter statement{{variable|length}}
outputs 3.length_is
.- Thelength_is
filter is used to evaluate if the length of a value is the size of a given argument. For example, if a variable containslatte
the tag and filter statement{% if variable|length_is:"7" %}
evaluates to false. For a list variable that contains['a','e','i']
the tag and filter statement{% if variable|length_is:"3" %}
evaluates to true.make_list
.- Themake_list
filter creates a list from a string or number. For example, for the filter and tag statement{% with mycharlist="mocha"|make_list %}
the mycharlist variable is assigned the list ['m', 'o', 'c', 'h', 'a']. For an integer variable that contains 724 the filter and tag statement{% with myintlist=variable|make_list %}
the myintlist is assigned the list ['7', '2', '4'].yesno
.- Theyesno
filter maps the value of a variable fromTrue
,False
andNone
to the strings yes,no,maybe. For example, if a variable evaluates toTrue
the filter statement{{variable|yesno}}
outputs yes, if the variable evaluates toFalse
the same statement outputs no and if the variable evaluates toNone
the same statement outputs maybe. Theyesno
filter also accepts custom messages as arguments. For example, if a variable evaluates toTrue
the filter statement{{variable|yesno:"yea,nay,novote"}}
outputs yea, if the variable evaluates toFalse
the same statement outputs nay and if the variable evaluates toNone
the same statement outputs novote.
Numbers
divisibleby
.- Thedivisibleby
filter returns a boolean value if a variable is divisible by a given value. For example, if a variable contains 20 the filter statement{{variable|divisibleby:"5"}}
returnsTrue
.filesizeformat
.-Thefilesizeformat
filter converts a number of bytes into a friendly file size string. For example, if a variable contains 250 the filter statement{{variable|filesizeformat}}
outputs 250 bytes, if it contains 2048 the output is 2 KB, if it contains 2000000000 the output is 1.9 GB.floatformat
.- Thefloatformat
filter rounds a floating-point number variable. Thefloatformat
filter can accept a positive or negative integer argument to round a variable a specific number of decimals. If zero is the argument the variable is rounded to the nearest integer. If no argument is used, thefloatformat
filter rounds to one decimal place, as if the argument where -1. For example, if a variable contains 9.53253 the filter statement{{variable|floatformat}}
outputs 9.5, for the same variable{{variable|floatformat:3}}
outputs 9.533, for{{variable|floatformat:-3}}
the output is 9.533 and for{{variable:floatformat:0}}
the output is 10; if a variable contains 9.00000 the filter statement{{variable|floatformat}}
outputs 9,{{variable|floatformat:3}}
outputs 9.000,{{variable|floatformat:-3}}
outputs 9 and{{variable|floatformat:0}}
outputs 9; and if a variable contains 9.37000 the filter statement{{variable|floatformat}}
outputs 9.4,{{variable|floatformat:3}}
outputs 9.370,{{variable|floatformat:-3}}
outputs 9.370 and{{variable|floatformat:0}}
outputs 9 9.370.The
floatformat
filter also supports ag
suffix added to the number argument to format the resulting number with theTHOUSAND_SEPARATOR
in a project's settings.py file. For example, if a variable contains 1100500.87000 the filter statement{{variable|floatformat:"g"}}
outputs 1,100,500.9, for the same variable{{variable|floatformat:"3g"}}
outputs 1,100,500.870, for{{variable|floatformat:"-3g"}}
the output is 1,100,500.870 and for{{variable:floatformat:"0g"}}
the output is 1,100,501.get_digit
.- Theget_digit
filter outputs the digit of a number variable, where 1 is the last digit, 2 is the second to last digit and so on. For example, if a variable contains 10257, the filter statement{{variable|get_digit:"1"}}
outputs 7 and the filter statement{{variable|get_digit:"3"}}
outputs 2. If the variable or argument is not an integer or if the argument is less than 1, theget_digit
filter output's the original variable value.phone2numeric
.- Thephone2numeric
filter converts mnemonic letters in phone numbers to digits. For example, if a variable contains 1-800-DJANGO the filter statement{{variable|phone2numeric}}
outputs 1-800-352646. Aphone2numeric
filter value doesn't necessarily need to process valid phone numbers, the filter simply converts letters to their equivalent telephone keypad numbers.
Note TheTHOUSAND_SEPARATOR
used by theg
suffix is dependent on locale (e.g. If a locale isen
the defaultTHOUSAND_SEPARATOR
is,
since it's the convention used to format numbers with thousands in english).
Strings
capfirst
.- Thecapfirst
filter capitalizes the first character of a string variable. For example, if a variable containshello world
the filter statement{{variable|capfirst}}
outputsHello world
.cut
.- Thecut
filter removes all values of a given argument from a string variable. For example, if a variable containsmocha latte
the filter statement{{variable|filter:"mocha"}}
outputslatte
. For the same variable the filter statement is{{variable|filter:" "}}
outputsmochalatte
.linenumbers
.- Thelinenumbers
filter adds line numbers to each string value separated by a new line. Listing 3-15 illustrates an example of thelinenumbers
filter.
Listing 3-15 Django linenumbers filter
# Variable definition variable = ["Downtown","Uptown","Midtown"] # Template definition with linenumbers filter {{variable|linenumbers}} # Output 1.Downtown 2.Uptown 3.Midtown
lower
.- Thelower
filter converts all values of a string variable to lowercase. For example, if a variable containsHello World
the filter statement{{variable|lower}}
outputshello world
.stringformat
.- Thestringformat
filter formats a value with Python string formatting syntax[4]. For example, if a variable contains7
the filter statement{{variable|stringformat:"03d"}}
outputs007
. Note thestringformat
filter does not require the leading%
used in Python string formatting syntax.pluralize
.- Thepluralize
filter returns a plural suffix based on the value of an argument. For example, if the variabledrink_count
contains 1 the filter statement"You have {{drink_count}} drink{{pluralize|drink_count}}"
outputs"You have 1 drink"
, if the variable contains 2 the same filter statement outputs"You have 2 drinks"
. By default, the pluralize filter uses the letter s which is the most common plural suffix. However, you can specify different singular and plural suffixes with additional arguments. For example, the filter statement"We have {{store_count}} business{{store_count|pluralize:"es"}}"
outputs"We have 1 business"
ifstore_count
is 1 or"We have 5 businesses"
ifstore_count
is 5. Another example is the filter statement"We have {{resp_number}} responsibilit{{resp_number|pluralize:"y","ies"}}"
which outputs"We have 1 responsibility"
ifresp_number
is 1 or"We have 3 responsibilities"
ifresp_number
is 3.slugify
.- Theslugify
filter converts a string to an ASCII-type string. This means a string in converted to lowercase, removes non-word characters (alphanumerics and underscores), strips leading and trailing white space, as well as converts spaces to hyphens. For example, if a variable containsWelcome to the #1 Coffeehouse!
the filter statement{{variable|slugify}}
outputswelcome-to-the-1-coffeehouse
. Theslugify
filter is typically used to normalize strings for urls and file paths.title
.- Thetitle
filter converts all first character values of a string variable to uppercase. For example, if a variable containshello world
the filter statement{{variable|title}}
outputsHello World
.truncatechars
.- Thetruncatechars
filter truncates a string to a given number of characters and appends an ellipsis sequence. For example, if a variable containsCoffeehouse started as a small store
the filter statement{{variable|truncatechars:20}}
outputsCoffeehouse started...
.truncatechars_html
.- Thetruncatechars_html
filter is similar to thetruncatechars
filter but is aware of HTML tags. This filter is designed for HTML content, so content isn't left with open HTML tags. For example, if a variable contains<b>Coffeehouse started as a small store</b>
the filter statement{{variable|truncachars_html:20}}
outputs<b>Coffeehouse start...</b>
.truncatewords
.- Thetruncatewords
filter truncates a string to a given number of words and appends an ellipsis sequence. For example, if a variable containsCoffeehouse started as a small store
the filter statement{{variable|truncatwords:3}}
outputsCoffeehouse started as...
.truncatewords_html
.- Thetruncatewords_html
filter is similar to thetruncatewords
filter but is aware of HTML tags. This filter is designed for HTML content, so content isn't left with open HTML tags. For example, if a variable contains<b>Coffeehouse started as a small store</b>
the filter statement{{variable|truncatwords_html:3}}
outputs<b>Coffeehouse started as...</b>
.upper
.- Theupper
filter converts all values of a string variable to uppercase. For example, if a variable containsHello World
the filter statement{{variable|lower}}
outputsHELLO WORLD
.wordcount
.- Thewordcount
filter counts the words in a string. For example, if a variable containsCoffeehouse started as a small store
the filter statement{{variable|wordcount}}
outputs 6.
Lists and dictionaries
dictsort
.- Thedictsort
filter sorts a list of dictionaries and returns new list sorted by a given key argument. For example, if a variable contains[{'name':'Downtown','city':'San Diego'}, {'name':'Uptown','city':'San Diego'},{'name':'Midtown','city':'San Diego'}]
the filter and tag statement{% with newdict=variable|dictsort:"name" %}
thenewdict
variable is assigned the list[{'name':'Downtown','city':'San Diego'},{'name':'Midtown','city':'San Diego'},{'name':'Uptown','city':'San Diego'}]
. Thedictsort
filter can also operate on lists of tuples or lists by specify an index number (e.g. {% with otherlist=listoftuples|dictsort:0 %}
) to sort by the first element of each tuple in the list).dictsortreversed
.- Thedictsortreversed
filter sorts a list of dictionaries and returns new list sorted in reverse by a given key argument. Thedictsortreversed
filter works likedictsort
except it returns the list in reverse order.join
.- Thejoin
filter joins a list with a string. The join filter works just like Python'sstr.join(list)
. For example, for a list variable that contains ['a','e','i','o','u'] the filter statement{{variable|join:"--"}}
outputs a--e--i--o--u.first
.- Thefirst
filter returns the first item in a list. For example, for a list variable that contains ['a','e','i','o','u'] the filter statement{{variable|first}}
outputs a.last
.- Thelast
filter returns the last item in a list. For example, for a list variable that contains ['a','e','i','o','u'] the filter statement{{variable|last}}
outputs u.random
.- Therandom
filter returns a random item in a list. For example, for a list variable that contains ['a','e','i','o','u'] the filter statement{{variable|random}}
could output a, e, i, o or u.slice
.- Theslice
filter returns the slice of a list. For example, for a list variable that contains ['a','e','i','o','u'] the filter statement{{variable|slice:":3"}}
outputs ['a','e','i'].unordered_list
.- Theunordered_list
outputs an HTML unordered list from a list variable. Listing 3-16 illustrates an example of the unordered_list filter.
Listing 3-16. Django unordered_list filter
# Variable definition variable = ["Stores",["San Diego",["Downtown","Uptown","Midtown"]]] # Template definition with linenumbers filter {{variable|unordered_list}} # Output <li>Stores <ul> <li>San Diego <ul> <li>Downtown</li> <li>Uptown</li> <li>Midtown</li> </ul> </li> </ul> </li>
Caution The first level of the unordered_list filter does not include opening or closing HTML <ul> tags
Spacing and special characters
addslashes
.- Theaddslashes
filter adds slashes to all quotes (i.e. it escapes quotes). Theaddslashes
filter is useful when Django templates are used to export data to other systems that require to escape quotes (e.g. CSV files). For example, if a variable containsToday's news
the filter statement{{variable|addslashes}}
outputsToday\'s
news.center
.- Thecenter
filter center aligns a value and pads it with additional white space characters until it reaches the given argument of characters. For example, if a variable containsmocha
the filter statement{{variable|center:"15"}}
outputs" mocha "
. (i.e. 5 spaces to the left of mocha, 5 spaces for mocha, 5 spaces to the right of mocha.ljust
.- Theljust
filter left aligns a value and pads it with additional white space characters until it reaches the given argument of characters. For example, if a variable containsmocha
the filter statement{{variable|ljust:"15"}}
outputs"mocha "
.(i.e. 5 spaces for mocha, 10 space padding).rjust
.- Therjust
filter right aligns a value and pads it with additional white space characters until it reaches the given argument of characters. For example, if a variable containslatte
the filter statement{{variable|rjust:"10"}}
outputs" latte"
."
(i.e. 5 space padding, 5 spaces for latte).escape
.- Theescape
filter escapes HTML characters from a value. Specifically with theescape
filter:<
is converted to<
,>
is converted to>
,'
(single quote) is converted to'
,"
(double quote) is converted to"
and&
is converted to&
.escapejs
.- Theescapejs
filter escapes characters into unicode strings which are often used for JavaScript strings. Though theescapejs
filter does not make a string HTML safe, it does protect against syntax errors when using templates to generate JavaScript/JSON. For example, if a variable contains "mocha\r\n \'price:2.25
" the filter statement{{variable|escapejs}}
outputs\u0022mocha\u000D\u000A \u0027price:2.25\u0022
.force_escape
.- Theforce_escape
filter escapes HTML characters from a value just like theescape
filter. The difference isforce_escape
is applied immediately and returns a new and escaped string. This is useful when you need multiple escaping or want to apply other filters to the escaped results. Normally, you'll use theescape
filter.json_script
.- Thejson_script
filter outputs a Python object as JSON, wrapped in an HTML<script>
element. Thejson_script
requires two arguments, a reference to a Python object (e.g. dictionary, list) and a string to use as theid
attribute value of the<script>
element. For example, for a dictionary that contains{'Django','3.2'}
the filter statement{{variable|json_script:"django-version"}}
outputs<script id="django-version" id="django-version" type="application/json">{"Django":"3.2"}</script>
.linebreaks
.- Thelinebreaks
filter replaces plain text line breaks with HTML tags, a single newline becomes an HTML line break (<br/>
) and a new line followed by a blank line becomes a paragraph break (</p>
). For example, if a variable contains385 Main\nSan Diego, CA
the filter statement{{variable|linebreaks}}
outputs<p>385 Main<br/>San Diego, CA</p>
.linebreaksbr
.- Thelinebreaksbr
filter converts all text variable new lines to HTML line breaks (<br/>
). For example, if a variable contains385 Main\nSan Diego, CA
the filter statement{{variable|linebreaksbr}}
outputs385 Main<br/>San Diego, CA
.striptags
.- Thestriptags
filter removes all HTML tags from a value. For example, if a variable contains<b>Coffee</b>house, the <i>best</i> <span>drinks</span>
the filter statement{{variable|striptags}}
outputsCoffeehouse, the best drinks
.safe
.- The safe filter marks a string as not requiring HTML escaping.safeseq
.- Thesafeseq
applies thesafe
filter to each element of a list. It's useful in conjunction with other filters that operate on a list, such as thejoin
filter (e.g.{{stores|safeseq|join:", "}})
. You wouldn't use thesafe
filter directly on list variables, as it would first convert the variable to a string, rather than working with the individual elements of a list.wordwrap
.- Thewordwrap
filter wraps words at a given character line length argument. Listing 3-17 illustrates an example of thewordwrap
filter.
Tip If you use the escape filter on contiguous variables, it's easier to wrap the variables with the {% autoescape %} tag to achieve the same results.
Caution The striptags filter uses very basic logic to strip HTML tags. This means there's a possibility a convoluted piece of HTML isn't fully stripped of tags. This is why content in variables passed through the striptags filter is automatically escaped and should never be marked as safe.
Listing 3-17. Django wordwrap filter
# Variable definition Coffeehouse started as a small store # Template definition with wordwrap filter for every 12 characters {{variable|wordwrap:12}} # Output Coffeehouse started as a small store
Development and testing
pprint
.- Thepprint
filter is a wrapper for Python'spprint.pprint()
. Thepprint
filter is useful during development and testing because it outputs the formatted representation of an object.
Urls
iriencode
.- Theiriencode
filter converts an Internationalized Resource Identifier (IRI) to a string that is suitable for inclusion in a URL. This is necessary if you're trying to use strings containing non-ASCII characters in a URL. For example, if a variable contains?type=cold&size=large
the filter statement{{variable|iriencode}}
outputs?type=cold&size=large
.urlencode
.- Theurlencode
filter escapes a value for use in a URL. For example, if a variable containshttp://localhost/drinks?type=cold&size=large
the filter statement{{variable|urlencode}}
outputshttp%3A//localhost/drinks%3Ftype%3Dcold%26size%3Dlarge
. Theurlenconde
filter assumes the/
character is safe. Theurlencode
filter can accept an optional argument with the characters that should not be escaped. An empty string can be provided when all characters should be escaped (e.g.{{variable|urlencode:""}}
outputshttp%3A%2F%2Flocalhost%2Fdrinks%3Ftype%3Dcold%26size%3Dlarge
).urlize
.- Theurlize
filter converts text URLs or email addresses into clickable HTML links. Thisurlize
filter works on links prefixed with http://, https://, or www.. Links generated by the urlize filter have arel="nofollow"
attribute added to them. For example, if a variable containsVisit http://localhost/drinks
the filter statement{{variable|urlize}}
outputsVisit <a href="http://localhost/drinks" rel="nofollow">http://localhost/drinks</a>
; if a variables containsContact support@coffeehouse.com
the filter statement{{variable|urlize}}
outputsContact <a href="mailto:support@coffeehouse.com">support@coffeehouse.com</a>
.urlizetrunc
.- Theurlizetrunc
filter converts text URLs and emails into clickable HTML links -- just like theurlize
filter -- except it truncates the url to a given number of characters that include an ellipsis sequence. For example, if a variable containsVisit http://localhost/drinks
the filter statement{{variable|urlizetrunc:20}}
outputsVisit <a href="http://localhost/drinks" rel="nofollow">http://localhost/...</a>
.
Caution The urlize and urlizetrunc filters should only be applied to variables with plain text. If applied to variables with HTML links the filter logic won't work as expected.