You are on page 1of 4

D J A N G O F I LT E R S

truncatewords_html are you ready to bring in


St r at e g y Guide

PLAYER 2?
{{ value|truncatewords_html:2 }}
Similar to truncatewords , except that it is aware of
HTML tags like truncatechars_html .
C O M M O N B U I LT- I N F I LT E R
unordered_list {{ value|unordered_list }} REFERENCE
Recursively takes a self-nested list and returns an
HTML unordered list – WITHOUT opening and closing
<ul> tags. add {{ value|add:"2" }}
Adds the argument to the value. If value is 4, then the
upper {{ value|upper }} output will be 6. Strings that can be coerced to integers
Uppercases the given value. "chunky bacon" will be summed, not concatenated.
becomes "CHUNKY BACON" .
capfirst {{ value|capfirst }}
urlencode {{ value|urlencode }} Capitalizes the first character of the value. If the first
Escapes a value for use in a URL. If value is character is not a letter, this filter has no effect. If
"https://www.example.org/foo?a=b&c=d", the value is "django", the output will be "django".
output will be "https%3A//www.example.org/
foo%3Fa%3Db%26c%3Dd". cut {{ value|cut:" " }}
Removes all values of arg from the given string.
urlize {{ value|urlize }} If value is "So cool", the output will be "Socool".
Converts URLs and email addresses in text into
clickable links. Apply this filter only to plain text. Six Feet Up is a software company focused on date {{ value|date }}
If value is "Check out sixfeetup.com" , the output helping tech teams regain momentum. We help or {{ value|date:"D d M Y" }}
will be "Check out <a href="http://sixfeetup. develop custom Python apps using Django, Formats a date according to the given format for the
com"rel="nofollow">sixfeetup.com</a>". current locale. When used without a format string, the
Pyramid and Plone. We help deploy apps on a
DATE_FORMAT format specifier is used. Additionally you
urlizetrunc {{ value|urlizetrunc:15 }} variety of private and public clouds, such as AWS.
can use the format specifiers "DATE_FORMAT" or "SHORT_
Combines urlize and truncatechars . If value is Companies like NASA and UCLA have sought out
DATE_FORMAT" which will cause the format specification
"Click www.djangoproject.com", the output would our passion for quality since 1999. We are proud to
in your settings. DATE_FORMAT or SHORT_DATE_FORMAT
be 'Click <a href="http://www.djangoproject. be a certified woman-owned business (WBE).
to be used. You can also localize the behavior of this
com"rel="nofollow">www.djangopr...</a>'. filter by setting USE_LI0N to True and LANUAGE_CODE to
a default locale. You can combine date with the time
wordwrap {{ value|wordwrap:5 }} filter to render a full representation of adatetime value.
Wraps words at specified line length. If value is Joel More info at:
{{ value|date:"D d M Y" }}{{ value|time:"H:i" }}
is a slug , the output would be: Joel S I X F E E T U P.C O M
is a default {{ value|default:"default text" }}
slug If value evaluates to False, uses the given default.
Otherwise, uses the value . If value is "", the output
yesno {{ value|yesno:"yeah,no,maybe" }} will be default text.
Maps values for True, False, and (optionally) None,
to the strings "yes" , "no" , "maybe", or a custom dictsort {{ value|dictsort:"name" }}
mapping passed as a comma-separated list. If value Takes a list of dictionaries and returns that list sorted by
is True, the output would be yeah. If value is None, the key given in the argument.
the output would be maybe . If value is:[ {'name': 'zed', 'age': 19}, {'name':
'amy', 'age': 22}, {'name': 'joe', 'age': 31}, ]
This publication is licensed under a Creative Commons then the output would be: [ {'name': 'amy', 'age':
Attribution-ShareAlike 3. 0 United States License. 22}, {'name': 'joe', 'age': 31}, {'name': 'zed',
'age': 19},]

S I X F E E T U P.C O M
divisibleby {{ value|divisibleby:"3" }} linebreaks {{ value|linebreaks }} stringformat {{ value|stringformat:"E" }}
Returns True if the value is divisible by the argument. Replaces line breaks in plain text with appropriate HTML; Formats the variable according to the argument
If value is 21, the output would be True . a single newline becomes an HTML line break using printf-style String Formatting syntax, with
(<br /) and a new line followed by a blank line becomes the exception that the leading "%" is dropped. In
escape {{ value|escape }} a paragraph break ( </p> ). If value is Joel\nis a slug , the example above, if value is 10, the output will be
Escapes a string’s HTML . Specifically, it makes these the output will be <p>Joel<br />is a slug</p> . 1.000000E+01 .
replacements:
< is converted to &lt;, > is converted to linebreaksbr {{ value|linebreaksbr }} striptags {{ value|striptags }}
&gt; , 'single quote) is converted to &#39; ," Converts all newlines in a piece of plain text to HTML line Makes all possible efforts to strip all [X]HTML tags.
(double quote) is converted to &quot; , and & is breaks ( <br /> ). striptags doesn't give any guarantee about its
converted to &amp; output being HTML safe so NEVER apply the safe filter
Applying escape to a variable that would normally have lower {{ value|lower }} to a striptags output. For something more robust,
auto-escaping applied to the result will only result in Converts a string into all lowercase. use the clean method of the bleach Python library.
one round of escaping being done. If you want multiple
escaping passes to be applied, use the pluralize {{ num_messages|pluralize}} time {{ value|time }}
force_escape filter. Returns a plural suffix if the value is not 1 . By default, Formats a time according to the given format. When
this suffix is ‘s’ . If num_messages is 1, the output used without a format string, the TIME_FORMAT format
filesizeformat {{ value|filesizeformat }} will beYou have 1 message. If num_messages is 2 specifier is used. {{ value|time:"TIME_FORMAT" }}{{
Formats the value like a ‘human-readable’ file size. the output will be You have 2 messages. For words value|time:"H:i" }}
If value is 123456789, the output would be 117.7 MB. that require a suffix other than ‘s’, you can provide an
alternate suffix as a parameter to the filter. You have {{ timesince
first {{ value|first }} num_buses }} bus{{ num_buses|pluralize:"es" }} . {{ blog_date|timesince:comment_date }}
Returns the first item in a list.
pprint pprint. pprint() timeuntil {{ conference_
floatformat {{ value|floatformat }} A wrapper around pprint. pprint()– for debugging. date|timeuntil:from_date }}
When used without an argument, rounds a floating- Formats a date as the time since an optional
point number to one decimal place. If used with a random {{ value|random }} second date without which the comparison point
numeric integer argument, rounds a number to that Returns a random item from the given list. If value is is now. If blog_date is a date instance representing
many decimal places. Passing0(zero) will round the the list ['a', 'b', 'c', 'd'], the output could be "b" . midnight on 1 June 2006 , and comment_date is a
float to the nearest integer. If value is 34.26234 for date instance for 08:00 on 1 June 2006 , then the
{{ value|floatformat }} the output will be 34.3 . If safe {{ var|safe }} following would return "8 hours". timeuntil works
value is 34.23234 for {{ value|floatformat:"0" }} the Marks a string as not requiring further HTML escaping similarly totimesince except that it measures the
output will be 34. prior to output. When auto escaping is off, this filter time from now until the given date or datetime .
has no effect. If you are chaining filters, a filter applied
iriencode {{ value|iriencode }} after safe can make the contents unsafe again. The title {{ value|title }}
Converts an IRI(Internationalized Resource following code prints the variable as is, unescaped: {{ Converts a string into titlecase. If value is "my FIRST
Identifier) to a string that is suitable for including in var|safe|escape }} post", the output will be "My First Post" .
a URL . If value is "?test=1&me=2", the output will
be"?test=1&amp;me=2" . slice {{ some_list|slice:":2" }} truncatechars {{ value|truncatechars:3 }}
Returns a slice of the list. Uses the same syntax as Truncates a string at the specified number of
join {{ value|join:" / " }} Python’s list slicing. If some_list is ['a', 'b', 'c'] , the characters.
Joins a list with a string, like Python’s str. join(list) output will be ['a', 'b'].
If value is the list ['a','b','c'] , the output will be the truncatechars_html
string "a / b / c" . slugify {{ value|slugify }} {{ value|truncatechars_html:9 }}
Converts to ASCII . Converts spaces to hyphens. Similar to truncatechars, except that it is aware of
last {{ value|last }} Removes characters that aren’t alphanumerics, HTML tags. If value is "<p>Joel is a slug</p>" , the
Returns the last item in a list. Given ['a','b','c'], the underscores, or hyphens. Converts to lowercase. Also output will be "<p>Joeli...</p>" .
output will be "c". strips leading and trailing whitespace. If value is "Joel is
a slug" , the output will be "joel-is-a-slug". truncatewords {{ value|truncatewords:2 }}
length {{ value|length }} Truncates a string after a certain number of words.
Returns the length of the value. This works for both
strings and lists.

S I X F E E T U P.C O M A R E Y O U R E A DY T O B RI N G I N P L AY E R 2
Using the Poll model from the canonical
Django tutorials, you might want to put
something into your templates that looks are you ready to bring in MAKING CUSTOM
D J A N G O T E M P L AT E TA G S
simply like:

{% show_choices_for_poll mypoll %}
PLAYER 2? St r at e g y Guide

Django’s templates are already pretty


To pull this off you’ll need a template for your powerful using just their built in capabilities,
tag, like poll_choices.html: but there is more you can do to increase
code re-use and keep your templates DRY.
<ul>
{% for choice in poll.choices %} The simplest is just a direct placeholder that
<li>{{ choice }}</li> will return arbitrary text to be inserted at the
{% endfor %} point of the tag.
</ul>
Start by creating a templatetags folder with
a blank __init__.py in your app. This is
and the tag to pass poll to the template: where you will locate your tag library called,
Six Feet Up is a software company focused on
perhaps, mylibrary.py
helping tech teams regain momentum. We help
@register.inclusion_tag(‘poll_choices.html’) develop custom Python apps using Django,
def show_choices_for_poll(poll): Pyramid and Plone. We help deploy apps on a Create a simple greeter tag like so:
return {‘poll’: poll} variety of private and public clouds, such as AWS.
Companies like NASA and UCLA have sought out
our passion for quality since 1999. We are proud to
# myapp/templatetags/mylibrary.py
be a certified woman-owned business (WBE).
The decorator does all of the heavy lifting from django import template
passing your returned dictionary as a context import random
to poll_choices.html template and returning More info at:
the rendered content back to your original S I X F E E T U P.C O M
# gives you a registry with decorators to
template. make it easy!
register = template.Library()
As powerful as this is, you may find it doesn’t
cover your particular use case. If that’s the @register.simple_tag
case, Django gives you all of the tools might def greet():
need to build a tag from the ground up. greeting = random.choice([‘Hello’,
If you find yourself in this situation, head ‘Yo’, ‘Hi’, ‘Hey’, ‘Oh Hai’, ])
on over to https://docs.djangoproject. return greeting
com/en/2.0/howto/custom-template- This publication is licensed under a Creative Commons
Attribution-ShareAlike 3.0 United States License.
tags/#advanced-custom-template-tags

S I X F E E T U P.C O M
If you need access to data in the context, you Arguments can also be passed: So, all together, you could use these in a
have to tell the decorator: template like so:

@register.simple_tag
@register.simple_tag(takes_context=True) def with_gusto(string): {% load mylibrary %}
def greet_current_user(context): return format_html(‘<b>{}!!!</b>’, string) <p>
return “Hai {}”.format(context.user. {% if request.user.is_anonymous %}
first_name) {% greet %}
Another common type of tag is the {% else %}
Assignment Tag. These can add data the {% greet_current_user %}
If you intend to include HTML in your output, template context for use by other tags but {% endif %}
be sure to mark it as safe. The recommended generate no output. For example, you might </p>
way is to use django.utils.html.format_ want to retrieve a list of active users by name: <p>
html which behaves just like str.format {% indypy_meetup_html %}
but includes some safety nets specific to {% with_gusto “IndyPy is a great python
including foreign HTML output: @register.assignment_tag user group” %}
def get_active_users(): </p>
“”” return first name and last initial
from django.utils.html import format_html for all active users. {% if request.user.is_authenticated %}
“”” {% get_active_users as all_users %}
@register.simple_tag return [ “{} {}.”.format(u.first_name, {% if all_users %}
def indypy_meetup_html(): u.last_name[0]) <p> Here are some people might
call_to_action = ‘Join us!’ for u in User.objects. meet:
format_string = ‘<a href=”https:// filter(active=True)] {{ all_users|join:”, “ }}
www.meetup.com/indypy/”>{}</a>’ </p>
return format_html(format_string, {% endif %}
call_to_action) Though you might normally do such things {% endif %}
in the view, it can some sometimes be more
convenient inside the template. To use this,
you need simply reference the tag and give it An even more powerful approach builds
name for the results, like so: upon the takes_context option, tag
arguments, and additional templates to
create inclusion tags. These tags display
{% get_active_users as all_users %} data in your template using another
template fed by data from your context!

S I X F E E T U P.C O M A R E Y O U R E A DY T O B RI N G I N P L AY E R 2

You might also like