Template context variables and filters¶
Variables¶
debug¶
Invoke pdb breakpoint from a template.
Example:
<h1>{{ site_name }}</h1>
{{ debug() }}
This will invoke function from websauna.template_debugger setting. The debugger is turned on only on development.ini. If there is no debugger configured, a warning is given.
See websauna.system.core.vars.debug()
for more information.
js_in_head¶
Should <script>
tags be placed in <head>
or end of <body>
.
See websauna.system.core.vars.js_in_head()
for more information.
now¶
Get the current time as UTC.
websauna.utils.time.now()
function.
Example:
See websauna.system.core.vars._now()
for more information.
on_demand_resource_renderer¶
Active instance of websauna.system.core.render.OnDemandResourceRenderer
managing dynamic CSS and JS. May be None.
See websauna.system.core.vars.on_demand_resource_renderer()
for more information.
site_author¶
Expose website URL from websauna.site_author
config variable to templates.
This is used in footer to display the site owner.
See websauna.system.core.vars.site_author()
for more information.
site_email_prefix¶
Expose website URL from websauna.site_email_prefix
config variable to templates.
This is used as the subject prefix in outgoing email. E.g. if the value is SuperSite
you’ll email subjects:
[SuperSite] Welcome to www.supersite.com
See websauna.system.core.vars.site_email_prefix()
for more information.
site_name¶
Expose website name from websauna.site_name
config variable to templates.
Example:
<div class="jumbotron text-center">
<h1>{{ site_name }}</h1>
<p class="lead text-center">
{{ site_tag_line }}
</p>
</div>
See websauna.system.core.vars.site_name()
for more information.
site_tag_line¶
Expose website URL from websauna.site_tag_line
config variable to templates.
This is used on the default front page to catch the attention of audience.
See websauna.system.core.vars.site_tag_line()
for more information.
site_time_zone¶
Expose website URL from websauna.site_time_zone
config variable to templates.
By best practices, all dates and times should be stored in the database using UTC time. This setting allows quickly convert dates and times to your local time.
Example:
<p>
<strong>Bar opens</strong>:
{{ opening_at|friendly_time(timezone=site_time_zone) }}
</p>
Default value is UTC
.
See timezone abbreviation list.
See websauna.system.core.vars.site_time_zone()
for more information.
site_title¶
Expose website name from websauna.site_title
config variable to templates.
This is the default <title>
tag.
Example:
<meta>
<title>My page - {{ site_title }}</title>
</meta>
See websauna.system.core.vars.site_title()
for more information.
site_url¶
Expose website URL from websauna.site_url
config variable to templates.
Note
You should not use this variable in web page templates. This variable is intended for cases where one needs templating without running a web server.
The correct way to get the home URL of your website is:
<a href="{{ request.route_url('home') }}">Home</a>
See websauna.system.core.vars.site_url()
for more information.
timedelta¶
Expose Python timedelta class to templates, so you can do relative time calculations.
For more information see datetime.timedelta
.
Example:
See websauna.system.core.vars._timedelta()
for more information.
Filters¶
admin_breadcrumbs¶
Render admin interface top breadcrumbs bar.
See websauna.system.admin.filters.admin_breadcrumbs()
for more information.
admin_url¶
Link to model in admin interface.
Takes an SQLAlchemy model instance as a filter argument and resolves its admin page. This requires that a model admin has been correctly registered for SQLAlchemy model.
Example:
{% if request.user and request.user.is_admin %}
<li>
<a class="btn btn-danger" href="{{ choice|admin_url("edit") }}">
Edit in admin
</a>
</li>
{% endif %}
Another example:
<li>
<a class="btn btn-danger" href="{{ choice|admin_url }}">
View in admin
</a>
</li>
See websauna.system.core.templatecontext.admin_url()
for more information.
arrow_format¶
Format datetime using Arrow formatter string.
Context must be a time/datetime object.
Arrow is a Python helper library for parsing and formatting datetimes.
Example:
<li>
Offer created at {{ offer.created_at|arrow_format('YYYYMMDDHHMMss') }}
</li>
See websauna.system.core.templatecontext.arrow_format()
for more information.
attr¶
Get an attribute of an object. foo|attr("bar")
works like
foo.bar
just that always an attribute is returned and items are not
looked up.
See Notes on subscriptions for more details.
batch¶
A filter that batches items. It works pretty much like slice just the other way round. It returns a list of lists with the given number of items. If you provide a second parameter this is used to fill up missing items. See this example:
<table>
{%- for row in items|batch(3, ' ') %}
<tr>
{%- for column in row %}
<td>{{ column }}</td>
{%- endfor %}
</tr>
{%- endfor %}
</table>
capitalize¶
Capitalize a value. The first character will be uppercase, all others lowercase.
d¶
If the value is undefined it will return the passed default value, otherwise the value of the variable:
{{ my_variable|default('my_variable is not defined') }}
This will output the value of my_variable
if the variable was
defined, otherwise 'my_variable is not defined'
. If you want
to use default with variables that evaluate to false you have to
set the second parameter to true:
{{ ''|default('the string was empty', true) }}
Changed in version 2.11: It’s now possible to configure the Environment
with
ChainableUndefined
to make the default filter work
on nested elements and attributes that may contain undefined values
in the chain without getting an UndefinedError
.
datetime¶
Format datetime in a certain timezone.
See websauna.system.core.templatecontext.filter_datetime()
for more information.
default¶
If the value is undefined it will return the passed default value, otherwise the value of the variable:
{{ my_variable|default('my_variable is not defined') }}
This will output the value of my_variable
if the variable was
defined, otherwise 'my_variable is not defined'
. If you want
to use default with variables that evaluate to false you have to
set the second parameter to true:
{{ ''|default('the string was empty', true) }}
Changed in version 2.11: It’s now possible to configure the Environment
with
ChainableUndefined
to make the default filter work
on nested elements and attributes that may contain undefined values
in the chain without getting an UndefinedError
.
dictsort¶
Sort a dict and yield (key, value) pairs. Because python dicts are unsorted you may want to use this function to order them by either key or value:
{% for item in mydict|dictsort %}
sort the dict by key, case insensitive
{% for item in mydict|dictsort(reverse=true) %}
sort the dict by key, case insensitive, reverse order
{% for item in mydict|dictsort(true) %}
sort the dict by key, case sensitive
{% for item in mydict|dictsort(false, 'value') %}
sort the dict by value, case insensitive
e¶
escape(s) -> markup
Convert the characters &, <, >, ‘, and ” in string s to HTML-safe sequences. Use this if you need to display text that might contain such characters in HTML. Marks return value as markup string.
See markupsafe._speedups.escape()
for more information.
escape¶
escape(s) -> markup
Convert the characters &, <, >, ‘, and ” in string s to HTML-safe sequences. Use this if you need to display text that might contain such characters in HTML. Marks return value as markup string.
See markupsafe._speedups.escape()
for more information.
escape_js¶
Make JSON strings to safe to be embedded inside <script> tag.
See websauna.system.core.templatecontext.escape_js()
for more information.
filesizeformat¶
Format the value like a ‘human-readable’ file size (i.e. 13 kB, 4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega, Giga, etc.), if the second parameter is set to True the binary prefixes are used (Mebi, Gibi).
float¶
Convert the value into a floating point number. If the
conversion doesn’t work it will return 0.0
. You can
override this default using the first parameter.
forceescape¶
Enforce HTML escaping. This will probably double escape variables.
format¶
Apply the given values to a printf-style format string, like
string % values
.
{{ "%s, %s!"|format(greeting, name) }}
Hello, World!
In most cases it should be more convenient and efficient to use the
%
operator or str.format()
.
{{ "%s, %s!" % (greeting, name) }}
{{ "{}, {}!".format(greeting, name) }}
friendly_time¶
Format timestamp in human readable format.
Context must be a datetimeobject
Takes optional keyword argument timezone which is a timezone name as a string. Assume the source datetime is in this timezone.
See websauna.system.core.templatecontext.friendly_time()
for more information.
from_timestamp¶
Convert UNIX datetime to timestamp.
Example:
<p>
Prestodoctor license expires: {{ prestodoctor.recommendation.expires|from_timestamp(timezone="US/Pacific")|friendly_time }}
</p>
- param context
UNIX timestamps as float as seconds since 1970
- return
Python datetime object
See websauna.system.core.templatecontext.from_timestamp()
for more information.
groupby¶
Group a sequence of objects by an attribute using Python’s
itertools.groupby()
. The attribute can use dot notation for
nested access, like "address.city"
. Unlike Python’s groupby
,
the values are sorted first so only one group is returned for each
unique value.
For example, a list of User
objects with a city
attribute
can be rendered in groups. In this example, grouper
refers to
the city
value of the group.
<ul>{% for city, items in users|groupby("city") %}
<li>{{ city }}
<ul>{% for user in items %}
<li>{{ user.name }}
{% endfor %}</ul>
</li>
{% endfor %}</ul>
groupby
yields namedtuples of (grouper, list)
, which
can be used instead of the tuple unpacking above. grouper
is the
value of the attribute, and list
is the items with that value.
<ul>{% for group in users|groupby("city") %}
<li>{{ group.grouper }}: {{ group.list|join(", ") }}
{% endfor %}</ul>
Changed in version 2.6: The attribute supports dot notation for nested access.
indent¶
Return a copy of the string with each line indented by 4 spaces. The first line and blank lines are not indented by default.
- param width
Number of spaces to indent by.
- param first
Don’t skip indenting the first line.
- param blank
Don’t skip indenting empty lines.
Changed in version 2.10: Blank lines are not indented by default.
Rename the indentfirst
argument to first
.
int¶
Convert the value into an integer. If the
conversion doesn’t work it will return 0
. You can
override this default using the first parameter. You
can also override the default base (10) in the second
parameter, which handles input with prefixes such as
0b, 0o and 0x for bases 2, 8 and 16 respectively.
The base is ignored for decimal numbers and non-string values.
join¶
Return a string which is the concatenation of the strings in the sequence. The separator between elements is an empty string per default, you can define it with the optional parameter:
{{ [1, 2, 3]|join('|') }}
-> 1|2|3
{{ [1, 2, 3]|join }}
-> 123
It is also possible to join certain attributes of an object:
{{ users|join(', ', attribute='username') }}
New in version 2.6: The attribute parameter was added.
last¶
Return the last item of a sequence.
Note: Does not work with generators. You may want to explicitly convert it to a list:
{{ data | selectattr('name', '==', 'Jinja') | list | last }}
list¶
Convert the value into a list. If it was a string the returned list will be a list of characters.
map¶
Applies a filter on a sequence of objects or looks up an attribute. This is useful when dealing with lists of objects but you are really only interested in a certain value of it.
The basic usage is mapping on an attribute. Imagine you have a list of users but you are only interested in a list of usernames:
Users on this page: {{ users|map(attribute='username')|join(', ') }}
You can specify a default
value to use if an object in the list
does not have the given attribute.
{{ users|map(attribute="username", default="Anonymous")|join(", ") }}
Alternatively you can let it invoke a filter by passing the name of the filter and the arguments afterwards. A good example would be applying a text conversion filter on a sequence:
Users on this page: {{ titles|map('lower')|join(', ') }}
Similar to a generator comprehension such as:
(u.username for u in users)
(u.username or "Anonymous" for u in users)
(do_lower(x) for x in titles)
Changed in version 2.11.0: Added the default
parameter.
New in version 2.7.
max¶
Return the largest item from the sequence.
{{ [1, 2, 3]|max }}
-> 3
- param case_sensitive
Treat upper and lower case strings as distinct.
- param attribute
Get the object with the max value of this attribute.
min¶
Return the smallest item from the sequence.
{{ [1, 2, 3]|min }}
-> 1
- param case_sensitive
Treat upper and lower case strings as distinct.
- param attribute
Get the object with the min value of this attribute.
model_url¶
A filter from model
to a string representing the absolute URL.
This filter calls pyramid.url.resource_url()
.
Note
This is being deprecated.
See pyramid_jinja2.filters.resource_url()
See pyramid_jinja2.filters.model_url_filter()
for more information.
pprint¶
Pretty print a variable. Useful for debugging.
With Jinja 1.2 onwards you can pass it a parameter. If this parameter is truthy the output will be more verbose (this requires pretty)
reject¶
Filters a sequence of objects by applying a test to each object, and rejecting the objects with the test succeeding.
If no test is specified, each object will be evaluated as a boolean.
Example usage:
{{ numbers|reject("odd") }}
Similar to a generator comprehension such as:
(n for n in numbers if not test_odd(n))
New in version 2.7.
rejectattr¶
Filters a sequence of objects by applying a test to the specified attribute of each object, and rejecting the objects with the test succeeding.
If no test is specified, the attribute’s value will be evaluated as a boolean.
{{ users|rejectattr("is_active") }}
{{ users|rejectattr("email", "none") }}
Similar to a generator comprehension such as:
(u for user in users if not user.is_active)
(u for user in users if not test_none(user.email))
New in version 2.7.
render_panel¶
Render a panel inline in a template.
Allows placing admin panels in templates directly.
Example how to include panel at the top of admin CRUD listing template:
{% block title %}
<h1>{{title}}</h1>
{{ context|render_panel(name="admin_panel", controls=False) }}
{% endblock %}
- param context
Any resource object, like ModelAdmin instance
- param name
registered panel name, like
admin_panel
- param kwargs
Passed to the panel function as is
- return
HTML string of the rendered panel
See websauna.system.core.templatecontext.render_panel()
for more information.
replace¶
Return a copy of the value with all occurrences of a substring
replaced with a new one. The first argument is the substring
that should be replaced, the second is the replacement string.
If the optional third argument count
is given, only the first
count
occurrences are replaced:
{{ "Hello World"|replace("Hello", "Goodbye") }}
-> Goodbye World
{{ "aaaaargh"|replace("a", "d'oh, ", 2) }}
-> d'oh, d'oh, aaargh
round¶
Round the number to a given precision. The first
parameter specifies the precision (default is 0
), the
second the rounding method:
'common'
rounds either up or down'ceil'
always rounds up'floor'
always rounds down
If you don’t specify a method 'common'
is used.
{{ 42.55|round }}
-> 43.0
{{ 42.55|round(1, 'floor') }}
-> 42.5
Note that even if rounded to 0 precision, a float is returned. If you need a real integer, pipe it through int:
{{ 42.55|round|int }}
-> 43
route_url¶
A filter from route_name
to a string representing the absolute URL.
This filter calls pyramid.url.route_url()
.
Example:
<a href="{{'login'|route_url}}">
Sign in
</a>
See pyramid_jinja2.filters.route_url_filter()
for more information.
safe¶
Mark the value as safe which means that in an environment with automatic escaping enabled this variable will not be escaped.
select¶
Filters a sequence of objects by applying a test to each object, and only selecting the objects with the test succeeding.
If no test is specified, each object will be evaluated as a boolean.
Example usage:
{{ numbers|select("odd") }}
{{ numbers|select("odd") }}
{{ numbers|select("divisibleby", 3) }}
{{ numbers|select("lessthan", 42) }}
{{ strings|select("equalto", "mystring") }}
Similar to a generator comprehension such as:
(n for n in numbers if test_odd(n))
(n for n in numbers if test_divisibleby(n, 3))
New in version 2.7.
selectattr¶
Filters a sequence of objects by applying a test to the specified attribute of each object, and only selecting the objects with the test succeeding.
If no test is specified, the attribute’s value will be evaluated as a boolean.
Example usage:
{{ users|selectattr("is_active") }}
{{ users|selectattr("email", "none") }}
Similar to a generator comprehension such as:
(u for user in users if user.is_active)
(u for user in users if test_none(user.email))
New in version 2.7.
slice¶
Slice an iterator and return a list of lists containing those items. Useful if you want to create a div containing three ul tags that represent columns:
<div class="columnwrapper">
{%- for column in items|slice(3) %}
<ul class="column-{{ loop.index }}">
{%- for item in column %}
<li>{{ item }}</li>
{%- endfor %}
</ul>
{%- endfor %}
</div>
If you pass it a second argument it’s used to fill missing values on the last iteration.
sort¶
Sort an iterable using Python’s sorted()
.
{% for city in cities|sort %}
...
{% endfor %}
- param reverse
Sort descending instead of ascending.
- param case_sensitive
When sorting strings, sort upper and lower case separately.
- param attribute
When sorting objects or dicts, an attribute or key to sort by. Can use dot notation like
"address.city"
. Can be a list of attributes like"age,name"
.
The sort is stable, it does not change the relative order of elements that compare equal. This makes it is possible to chain sorts on different attributes and ordering.
{% for user in users|sort(attribute="name")
|sort(reverse=true, attribute="age") %}
...
{% endfor %}
As a shortcut to chaining when the direction is the same for all attributes, pass a comma separate list of attributes.
{% for user users|sort(attribute="age,name") %}
...
{% endfor %}
Changed in version 2.11.0: The attribute
parameter can be a comma separated list of
attributes, e.g. "age,name"
.
Changed in version 2.6: The attribute
parameter was added.
static_url¶
A filter from path
to a string representing the absolute URL.
This filter calls pyramid.url.static_url()
.
Example:
<link rel="stylesheet" href="{{'yourapp:static/css/style.css'|static_url}}" />
See pyramid_jinja2.filters.static_url_filter()
for more information.
string¶
soft_unicode(object) -> string
Make a string unicode if it isn’t already. That way a markup string is not converted back to unicode.
See markupsafe._speedups.soft_unicode()
for more information.
sum¶
Returns the sum of a sequence of numbers plus the value of parameter ‘start’ (which defaults to 0). When the sequence is empty it returns start.
It is also possible to sum up only certain attributes:
Total: {{ items|sum(attribute='price') }}
Changed in version 2.6: The attribute parameter was added to allow suming up over attributes. Also the start parameter was moved on to the right.
timestruct¶
Render both humanized time and accurate time.
show_timezone
target_timezone
source_timezone
format
See websauna.system.core.templatecontext.timestruct()
for more information.
title¶
Return a titlecased version of the value. I.e. words will start with uppercase letters, all remaining characters are lowercase.
to_json¶
Converts Python dict to JSON, safe to be placed inside <script> tag.
Example:
{#
Export server side generated graph data points
to Rickshaw client side graph rendering
#}
{% if graph_data %}
<script>
window.graphDataJSON = "{{ graph_data|to_json }}";
</script>
{% endif %}
- param context
Takes Python dictionary as input
- param safe
Set to False to not to run
escape_js()
on the resulting JSON. True by default.- return
JSON string to be included inside HTML code
See websauna.system.core.templatecontext.to_json()
for more information.
tojson¶
Dumps a structure to JSON so that it’s safe to use in <script>
tags. It accepts the same arguments and returns a JSON string. Note that
this is available in templates through the |tojson
filter which will
also mark the result as safe. Due to how this function escapes certain
characters this is safe even if used outside of <script>
tags.
The following characters are escaped in strings:
<
>
&
'
This makes it safe to embed such strings in any place in HTML with the notable exception of double quoted attributes. In that case single quote your attributes or HTML escape it in addition.
The indent parameter can be used to enable pretty printing. Set it to the number of spaces that the structures should be indented with.
Note that this filter is for use in HTML contexts only.
New in version 2.9.
truncate¶
Return a truncated copy of the string. The length is specified
with the first parameter which defaults to 255
. If the second
parameter is true
the filter will cut the text at length. Otherwise
it will discard the last word. If the text was in fact
truncated it will append an ellipsis sign ("..."
). If you want a
different ellipsis sign than "..."
you can specify it using the
third parameter. Strings that only exceed the length by the tolerance
margin given in the fourth parameter will not be truncated.
{{ "foo bar baz qux"|truncate(9) }}
-> "foo..."
{{ "foo bar baz qux"|truncate(9, True) }}
-> "foo ba..."
{{ "foo bar baz qux"|truncate(11) }}
-> "foo bar baz qux"
{{ "foo bar baz qux"|truncate(11, False, '...', 0) }}
-> "foo bar..."
The default leeway on newer Jinja versions is 5 and was 0 before but can be reconfigured globally.
unique¶
Returns a list of unique items from the given iterable.
{{ ['foo', 'bar', 'foobar', 'FooBar']|unique|list }}
-> ['foo', 'bar', 'foobar']
The unique items are yielded in the same order as their first occurrence in the iterable passed to the filter.
- param case_sensitive
Treat upper and lower case strings as distinct.
- param attribute
Filter objects with unique values for this attribute.
urlencode¶
Quote data for use in a URL path or query using UTF-8.
Basic wrapper around urllib.parse.quote()
when given a
string, or urllib.parse.urlencode()
for a dict or iterable.
- param value
Data to quote. A string will be quoted directly. A dict or iterable of
(key, value)
pairs will be joined as a query string.
When given a string, “/” is not quoted. HTTP servers treat “/” and
“%2F” equivalently in paths. If you need quoted slashes, use the
|replace("/", "%2F")
filter.
New in version 2.7.
urlize¶
Converts URLs in plain text into clickable links.
If you pass the filter an additional integer it will shorten the urls to that number. Also a third argument exists that makes the urls “nofollow”:
{{ mytext|urlize(40, true) }}
links are shortened to 40 chars and defined with rel="nofollow"
If target is specified, the target
attribute will be added to the
<a>
tag:
{{ mytext|urlize(40, target='_blank') }}
Changed in version 2.8+: The target parameter was added.
uuid_to_slug¶
Convert UUID object to a base64 encoded slug.
Example:
{% for question in latest_question_list %}
<li>
<a href="{{ route_url('details', question.uuid|uuid_to_slug) }}">
{{ question.question_text }}
</a>
</li>
{% endfor %}
See websauna.system.core.templatecontext.uuid_to_slug()
for more information.
wordwrap¶
Wrap a string to the given width. Existing newlines are treated as paragraphs to be wrapped separately.
- param s
Original text to wrap.
- param width
Maximum length of wrapped lines.
- param break_long_words
If a word is longer than
width
, break it across lines.- param break_on_hyphens
If a word contains hyphens, it may be split across lines.
- param wrapstring
String to join each wrapped line. Defaults to
Environment.newline_sequence
.
Changed in version 2.11: Existing newlines are treated as paragraphs wrapped separately.
Changed in version 2.11: Added the break_on_hyphens
parameter.
Changed in version 2.7: Added the wrapstring
parameter.
xmlattr¶
Create an SGML/XML attribute string based on the items in a dict. All values that are neither none nor undefined are automatically escaped:
<ul{{ {'class': 'my_list', 'missing': none,
'id': 'list-%d'|format(variable)}|xmlattr }}>
...
</ul>
Results in something like this:
<ul class="my_list" id="list-42">
...
</ul>
As you can see it automatically prepends a space in front of the item if the filter returned something unless the second parameter is false.