Arithmetic filters
Many of the filters in this section were designed to act on Query
Report results. Our report results that return a single value are
wrapped in a
<span> html tag. For example, a variable containing a report result would actually hold
<span class="query-">555</span>
not '555.' While the HTML will render invisibly, built-in filters like
add and subtract cannot handle a such a string. Many of our filters
will strip away the HTML tag to pull out the report value.
More precisely, the filters extract the first occurrence of an integer or real number.
add
The filter
add
returns the sum of the argument and the value. This overrides Django's
built-in filter which works on integers only. This filter can extract a
number from the value and argument and add both floats and integers,
rounding results to two decimal places (for adding dollar amounts, for
example).
For example:
if a is
<span class="query-">25.50</span> and b is
30
returns 55.25
commify
The filter commify
renders a numeric value with commas as the thousands separator. This
filter currently only works on integers, but like arithmetic filters
above it will extract an integer from a string containing non-numeric
characters.
humanize_seconds
The filter
humanize_seconds
takes a numeric argument (as a string or an integer) of a number of
seconds and converts it to a smart string of the form "X days, X hours, X
minutes, X seconds" with an appropriate level of detail (no more than
two units).
For example:
{{ 5982|humanize_seconds }} and {{ 200000|humanize_seconds }}
return '1 hour, 39 minutes' and '2 days, 7 hours', respectively
mod
The filter
mod
returns the integer remainder of the value divided by the argument.
Value and argument are coerced to be integers and this essentially
exposes Python's
% operator to you.
For example:
multiply
The filter
multiply returns the product of the value mutiplied by the argument.
For example:
{{ suggested_ask|multiply:"2" }}
returns the user's suggested ask as defined on your page times two.
percent_of
The filter
percent_of returns the value divided by the argument, formatted as a percentage with one decimal place.
For example:
If value is 72 and argument is 499
{{ value|percent_of:argument }}
returns '14.4%'
percent_of2
The filter percent_of2 functions like percent_of but returns the percentage formatted to two decimal places.
subtract
The filter subtract returns the difference of the value and the argument. Like add, this overrides Django's filter.
Text related filters
akid
The filter akid takes a string value and a user object as its argument (or anything with either an attribute or method token) and modifies all client links in the string by appending ?akid=[token] or &akid=[token]
if the url has a querystring. Client links are those where the
top-level domain is actionkit.com or one of your hostnames. Links
appearing inside a src="" attribute, such as images, are excluded.
ak_field
The filter
ak_field is used to translate a field name in your page templates. For example, we could write:
{% filter ak_field:"email" %}E-mail{% endfilter %}
Django's built-in
filter template tag ensures that
ak_field applies to the entire text contained in the tag. The text "E-mail" is replced by the translation for
field_email in the selected language for the page being viewed. If no translated text is avilable, "E-mail" will be displayed by default.
ak_text
The filter
ak_text works like
ak_field
above and can be used to translate any custom phrases you want. First,
go to Pages > Related Tools > Manage Languages. Click Edit on the
language your page will use for translation and click "Translate
another piece of text" at the bottom. Enter a label in the left box and
the translation into the right box.
For example, if the label is "hokey_pokey", include this block in your template:
{% filter ak_text:"hokey_pokey" %}
Do the hokey pokey and turn yourself around (that's what it's all about)
{% endfilter %}
The text will be replaced by your translation, with the enclosed text being used as a default.
blank_money_field
The filter blank_money_field filters a string containing a field for a donation amount so that the field is blank instead of 0.00.
break_long_words
The filter
break_long_words
takes a string value and returns the string with a space inserted in
any long stretches of non-whitespace characters. The argument specifies
how many characters are left untouched before breaking up a word; it is
optional and defaults to 30.
For example:
if alpha =
abcdefghijklmnopqrstuvwxyz0123456789
{{ alpha|break_long_words:15 }}
yields
u'abcdefghijklmno pqrstuvwxyz0123 456789'
collapse_spaces
The filter collapse_spaces
takes a string value and returns the string with runs of whitespace
replaced by a single space or a single new line (depending on whether
the whitespace was within one line or spanned more than one line,
respectively).
endswith
The filter endswith returns True if value ends with arg. This filter exposes Python's <string>.endswith(<string>) method.
escapeall
The filter escapeall takes a string value and escapes both accented characters and HTML-unsafe ones.
has_8bit
This one is confusingly named, for legacy reasons. The filter has_8bit returns True or False depending on whether a string contains characters outside the range \\x00 to \\xff. In other words, it will be True for strings that contain multi-byte Unicode characters.
has_rtl
The filter has_rtl returns True or False depending on whether a string contains right-to-left characters in it, e.g. Hebrew and Arabic characters.
is_defined
The filter is_defined returns True if the value is not None.
is_nonblank
The filter is_nonblank returns True if the string does not appear blank when rendered - that is, it consists of more than just whitespace and invisible HTML.
For example the strings with spaces and \t , and , and <p></p><div class="lol"> </div> would all return False.
json
The filter json returns the value encoded as a JSON data structure without any HTML escaping.
login_string
The filter
login_string
is used in mailings to supply the login hash for an ActionKit user to
access event pages, recurring donation management pages and any other
pages that require login. This goes in the links query string as
?i=[login_string]. It expects to be passed a dict with a key
id that contains the user_id.
For example:
http://roboticdogs.actionkit.com/event/{{ page_name }}/tools/?i={{ user|login_string }}
matches
The filter matches returns True
if value contains the regular expression in arg case insensitively.
This filter uses Python's re module. Further information on regular
expression syntax can be found in the documentation.
no_blank_paragraphs
The filter
no_blank_paragraphs takes a string and removes HTML paragraphs that would render as blank (whitespace or invisible HTML).
For example:
if text is
<p class='content'> </p>,
{{ text|no_blank_paragraphs }}
returns an empty string
nospam
The filter nospam
filters a string value by returning a blank string if the value
contains HTML, links, or profanity. This can be used to remove spammy
comments or other user input.
pretty_json
The filter pretty_json returns the value rendered as a pretty-fied JSON structure: with indentations, sort keys in dictionaries and HTML escaping.
readable_identifier
The filter readable_identifier take a string value; it replaces each underscore with a space, capitalizes the first character and puts the rest in lowercase.
redirect_links
The filter redirect_links takes a string value and rewrites links as redirect urls. Links appearing inside a src="" attribute and those with no_redirect=1 or no_akid=1 in the query string are excluded.
referring_akid
The filter referring_akid takes a string value and a user object as its argument (or anything with an attribute or method of token) and modifies all client links in the string by appending ?referring_akid=[token] or &referring_akid=[token]
if the url has a querystring. Client links are those where the
top-level domain is actionkit.com or one of your hostnames. Links
appearing inside a src="" attribute, such as images, are excluded.
replacechar
The filter
replacechar
takes a string value that it acts on and a two character string for an
argument. The argument consists of the character to be replaced
followed by the character it is replaced with. The replacement is done
for every occurrence within the value.
For example:
{{ "1.2 km"|replacechar:".," }}
returns 1,2 km. This filter is useful for display distance for countries that use the comma in the standard display.
single_line
The filter single_line
takes a string value and returns the string with newlines (and adjacent
whitespace) replaced by a single space. This is useful for text-only
versions of transactional mail, for instance.
spaces_to_underscores
The filter spaces_to_underscores takes a string value; it replaces each space with an underscore and converts the string to lowercase.
star_required
The filter star_required takes a string value containing the HTML for a field and searches for class="required". If found, it adds a * to show that the field is required.
startswith
The filter startswith returns True if the string value begins with arg (as a substring). This filter exposes Python's <string>.startswith(<string>) method.
strip
The filter strip returns the string value with leading and trailing whitespace removed. This exposes Python's <string>.strip() method.
strip_nondigits
The filter strip_nondigits
takes a string value and returns only the 0-9 digits contained within
it. This is useful for stripping away any non-numeric formatting so
that the resulting numeric string can be passed to an arithmetic tag.
If you are writing a Dashboard Report that combines the integer results
of several Query Reports, use this filter to remove the HTML formatting
from the Query Report result like <span class="query-">555</span> so that it can be used in intermediate computations.
tag_links
The filter
tag_links
takes a string value and an argument consisting of a tag. Client links
(with the top-level domain of actionkit.com or one of your registered
domains) in the string have
?[tag] appended, or
&[tag] if a query string already exists. Links appearing inside an
src="" attribute, such as images, are excluded.
For example:
if text is
"Click to sign an important petition:
<a href='http://roboticdogs.actionkit.com/sign/robotic_kitties'>
http://roboticdogs.actionkit.com/sign/robotic_kitties</a>"
then
{{ text|tag_links:'dog=yes'|safe }}
returns
"Click to sign an important petition:
<a href='http://roboticdogs.actionkit.com/sign/robotic_kitties?dog=yes'>
http://roboticdogs.actionkit.com/sign/robotic_kitties?dog=yes</a>"
truncateeachword
The filter
trunchateeachword
takes a string value and a numeric argument. If any word in the string
is longer than the specified character length, that word is cut off
with the ellipsis "..." appended.
For example:
if text is
reallylongword anotherendlessword
{{ text|truncateeachword:8 }}
returns
u'reallylo... anothere...'
truncatehtml
The filter
truncatehtml
takes a string value and a numeric argument. If the length of the HTML
string exceeds the specified character length, the string is cut off
with the ellipsis "..." appended. However, care is taken not to cut off
the string in the middle of an HTML entity, and after the ellipsis any
open HTML tags are closed. HTML escaping is also applied to the output.
For example:
if document is the string
<html><body><p>ActionKit is built by We Also Walk Dogs.</p></body></html>, then
{{ document|truncatehtml:20|safe }}
yields
u'<html><body><p>ActionKit is built b...</p></body></html>
truncateletters
The filter truncateletters
takes a string value and a numeric argument. If the length of the
string exceeds the number of characters in arg, the string gets
truncated to that length and "..." is appended. This can be useful for
keeping long page titles and mailing subjects to a manageable size.
List related filters
columns
The filter
columns acts on a list to break it into sublists (
rows) of n elements (
columns)
each. When the list does not divide evenly by n, this method divides
the first columns evenly, leaving the remainder in the last column. In
more precise mathematical terms, in the cases when n does not divide
then
len(value), it takes the columns to have length
int(1 + (len(value)/n)). The rows have length n or n-1.
For example:
if data is range(0,10):
returns [[0, 4, 8], [1, 5, 9], [2, 6], [3, 7]]
i.e.:
[[0, 4, 8],
[1, 5, 9],
[2, 6],
[3, 7]]
This filter is used in ActionKit in the Donate
template (in the Original templateset and any others that haven't been
too heavily rewritten). We use the following code to format the
donation amount choices into three columns:
<div id="amount_list">
<p><label for="amount">Donation Amount:</label>
<table border="1">
{% for row in amounts|columns:3 %}
<tr>
{% for amount in row %}
... code to display the radio buttons and the amounts ...
{% endfor %}
</tr>
{% endfor %}
</table>
</div>
We've set up a page illustrating this use of columns with 13 donation amounts at https://roboticdogs.actionkit.com/donate/columnexample/#1.
See also:
contains
The filter
contains returns true if the value contains the arg.
For example:
if zips is ['10001', '10003', '10011']
{{ zips|contains:'10001' }}
would be True.
is_in
The filter
is_in is the reverse of contains; it returns true if the arg contains the value.
For example:
islice
The filter
islice returns a slice of the list (or generator) object. This has the same syntax as Python's list slicing. For example,
If list is ['we', 'also', 'walk', 'dogs'],
returns ['also', 'walk'].
This filter is similar to Django's built-in filter
slice but uses Python's
itertools.islice().
join
The filter
joins
takes a list for its value and a delimiter as its argument and returns a
string of lists elements joined by the delimiter. This mirrors the
functionality of Python's
delimiter.join(<list>) method. The argument is mandatory.
For example:
If list is ['we', 'also', 'walk', 'dogs'],
returns the string
u'wealsowalkdogs'
limit
The filter limit returns the first n items (specified by the arg) of a list (supplied as the value).
nth
The filter
nth
returns n-th item (specified by the arg, counting from 0) of a list
(supplied as the value). While Django already supports list-indexing in
templates, e.g. {{ states.4 }}, our filter works in daisy chains of
several filters.
For example:
if states is ['AL', 'CA', 'CA', 'OR'],
{{ states|unique|nth:2 }}
will return
OR
but
{{ states|unique.2 }} does not parse.
rows
The filter
rows
acts on a list to break it into n "rows" (sublists). When the list
does not divide evenly by n, this method divides the first rows evenly,
leaving the remainder in the last row. In more precise mathematical
terms, in this method when n does not divide the
len(value), it takes the rows to have length
int(1 + (len(value)/n)). This can lead to some rows being empty in cases where n is almost as big as len(value).
Note the the order of the elements in value is preserved.
For example:
if data is range(0,10)
returns [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9]]
and
returns [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [], [], [], []]
rows_distributed
The filter
rows_distributed acts like rows,
but breaks up the value into n rows in an intuitive manner. A list of
length 10 is broken into 4 rows as 3, 3, 2, 2 not 3, 3, 3, 1.
For example:
if data is as above
{{ data|rows_distributed:9 }}
gives us [[0, 1], [2], [3], [4], [5], [6], [7], [8], [9]]
shuffle
The filter shuffle takes a list for a value and returns the list with its items shuffled randomly. This filter does not take an argument.
split
The filter
splits
a string value on a given separator (default is whitespace) and returns
a list. This could be useful for constructing loops. The
functionality is analogous to Python's
.split() method for strings.
For example:
If value is the string "We Also Walk Dogs"
returns the list
[u'We', u'Also', u'Walk', u'Dogs']
Another example:
If months is the string "January February March April"
{% for month in months|split %}
---something involving {{month}}---
{% endfor %}
creates a loop where
{{month}} takes the values "January", "February", etc in turn.
unique
The filter
unique takes a sequence type (list, tuple, etc) and filters it to return a generator object with only distinct elements.
We limit this to the first 100 items to avoid problems with overly large inputs.
unique accepts an optional argument, key, and if present filters the elements for distinct values of
getattr(item, key, item) for each item in value.
For example:
if value is ['Action', 'Action', 'Kit', 'Action', 'Kit']
returns a generator object that yields 'Action' and then 'Kit'.
Miscellaneous filters
chart_data
The filter chart_data
takes a list of numeric values and returns a comma-separated string for
use in the Google charts some of our built-in Dashboard Reports use.
If value has more or fewer than 12 elements, items are truncated from
the left or zeroes are padded onto the right.
chart_data_misc
The filter chart_data_misc
takes a list of numeric values and returns a comma-separated string for
use in the Google charts some of our built-in Dashboard Reports use.
chart_labels
The filter chart_labels
takes a list of numeric values and returns a pipe ('|') separated
string for use in the Google charts some of our built-in Dashboard
Reports use.
chart_spacing and chart_scale
These filters are used in the Google charts in some of our built-in
Dashboard Reports. They act on the chart data in order to determine an
appropriate y-axis scale and y-axis spacing for the chart.
country_names
The filter
country_names
takes a string consisting of a two-letter ISO language code, for
example 'en' or 'fr' or 'pl.' It returns a list of tuples, with tuples
of the form (
<english country name>,
<country name in the given language>) for each country.
For example:
returns a list with elements such as (
u'Poland', u'Pologne').
days_past
The filter
``days_past`
can be used in your dashboard reports to generate a list of timestamps
for the last several days, the number of which is specified by the
argument. The value supplied to the filter must be a Python datetime
object. You can use this to build a table or Google chart of data by
day.
For example:
if now holds datetime.now() and the present time is '2013-01-15 20:00:00',
returns ['2012-01-10 00:00:00', '2012-01-11 00:00:00', '2012-01-12
00:00:00', '2013-01-13 00:00:00', '2013-01-14 00:00:00', '2013-01-15
00:00:00']
make_urls_absolute
This filter takes an HTML string for its value and tries to convert
relative URLs into absolute ones. Takes a True/False argument for
whether to use SSL.
month_ago
The filter
month_ago acts on a MySQL style datetime value and subtracts one month.
For example:
{{ '2012-06-01 15:15:30'|month_ago }}
returns '2012-05-01 15:15:30'
month_year
The filter
month_year acts on a MySQL style datetime value to return a prettified Month Year string we can use in monthly reports.
For example,
{{ "2010-06-01 01:02:03"|month_year }}
returns "June 2012".
months_past
The filter
``months_past`
is used in the built-in progress report dashboards to generate a list
of the last several months, the number of which is specified by the
argument. The value supplied to the filter must be a Python datetime
object. This can be used to build a table with a row of data for each
month or to build a table for a Google chart.
For example:
if now holds datetime.now() and the present time is '2012-06-01 19:00:00',
returns ['2011-07-01 00:00:00', '2011-08-01 00:00:00', '2011-09-01
00:00:00', '2011-10-01 00:00:00', '2011-11-01 00:00:00', '2011-12-01
00:00:00', '2012-01-01 00:00:00', '2012-02-01 00:00:00', '2012-03-01
00:00:00', '2012-04-01 00:00:00', '2012-05-01 00:00:00', '2012-06-01
00:00:00']
months_pastyr
The filter months_pastyr has been deprecated. Please see months_past.
months_until
The filter
months_until
has a specific use in the built-in progress report dashboards. It acts
on a Python datetime object that holds the current time, and returns a
list that can be iterated over with an entry for each month in the
calendar year up to now.
For example:
if now holds datetime.now() and the present time is '2012-06-01 19:00:00',
returns ['2012-01-01 00:00:00', '2012-02-01 00:00:00', '2012-03-01
00:00:00', '2012-04-01 00:00:00', '2012-05-01 00:00:00', '2012-06-01
00:00:00']
weeks_past
The filter
weeks_past
can be used in your dashboard reports to generate a list of timestamps
for the last several weeks, the number of which is specified by the
argument. The value supplied to the filter must be a Python datetime
object. You can use this to build a table or Google chart of data by
week.
For example:
if now holds datetime.now() and the present time is '2013-01-15 20:00:00',
returns ['2012-12-11 00:00:00', '2012-12-18 00:00:00', '2012-12-25
00:00:00', '2013-01-01 00:00:00', '2013-01-08 00:00:00', '2013-01-15
00:00:00']
No comments:
Post a Comment