module documentation

Built-in template filters used with the | operator.
Constant F Undocumented
Constant FILTERS Undocumented
Constant K Undocumented
Constant V Undocumented
Class _​Group​Tuple Undocumented
Class ​Has​HTML Undocumented
Function ​_min​_or​_max Undocumented
Function ​_prepare​_attribute​_parts Undocumented
Async Function async​_select​_or​_reject Undocumented
Function contextfilter Pass the context as the first argument to the decorated function.
Function do​_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.
Function do​_batch No summary
Function do​_capitalize Capitalize a value. The first character will be uppercase, all others lowercase.
Function do​_center Centers the value in a field of a given width.
Function do​_default If the value is undefined it will return the passed default value, otherwise the value of the variable:
Function do​_dictsort Sort a dict and yield (key, value) pairs. Python dicts may not be in the order you want to display them in, so sort them first.
Function do​_filesizeformat No summary
Async Function do​_first Undocumented
Function do​_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.
Function do​_forceescape Enforce HTML escaping. This will probably double escape variables.
Function do​_format Apply the given values to a `printf-style`_ format string, like string % values.
Async Function do​_groupby Undocumented
Function do​_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.
Function do​_int No summary
Async Function do​_join Undocumented
Function do​_last Return the last item of a sequence.
Async Function do​_list Undocumented
Function do​_lower Convert a value to lowercase.
Async Function do​_map Undocumented
Function do​_mark​_safe Mark the value as safe which means that in an environment with automatic escaping enabled this variable will not be escaped.
Function do​_mark​_unsafe Mark a value as unsafe. This is the reverse operation for safe.
Function do​_max Return the largest item from the sequence.
Function do​_min Return the smallest item from the sequence.
Function do​_pprint Pretty print a variable. Useful for debugging.
Function do​_random Return a random item from the sequence.
Async Function do​_reject Undocumented
Async Function do​_rejectattr Undocumented
Function do​_replace No summary
Function do​_reverse Reverse the object or return an iterator that iterates over it the other way round.
Function do​_round Round the number to a given precision. The first parameter specifies the precision (default is 0), the second the rounding method:
Async Function do​_select Undocumented
Async Function do​_selectattr Undocumented
Async Function do​_slice Undocumented
Function do​_sort Sort an iterable using Python's sorted.
Function do​_striptags Strip SGML/XML tags and replace adjacent whitespace by one space.
Async Function do​_sum Undocumented
Function do​_title Return a titlecased version of the value. I.e. words will start with uppercase letters, all remaining characters are lowercase.
Function do​_tojson Serialize an object to a string of JSON, and mark it safe to render in HTML. This filter is only for use in HTML documents.
Function do​_trim Strip leading and trailing characters, by default whitespace.
Function do​_truncate No summary
Function do​_unique Returns a list of unique items from the given iterable.
Function do​_upper Convert a value to uppercase.
Function do​_urlencode Quote data for use in a URL path or query using UTF-8.
Function do​_urlize Convert URLs in text into clickable links.
Function do​_wordcount Count the words in that string.
Function do​_wordwrap Wrap a string to the given width. Existing newlines are treated as paragraphs to be wrapped separately.
Function do​_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:
Function environmentfilter Pass the environment as the first argument to the decorated function.
Function evalcontextfilter Pass the eval context as the first argument to the decorated function.
Function ignore​_case For use as a postprocessor for make_attrgetter. Converts strings to lowercase and returns other types as-is.
Function make​_attrgetter No summary
Function make​_multi​_attrgetter No summary
Function prepare​_map Undocumented
Function prepare​_select​_or​_reject Undocumented
Function select​_or​_reject Undocumented
Function sync​_do​_first Return the first item of a sequence.
Function sync​_do​_groupby No summary
Function sync​_do​_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:
Function sync​_do​_list Convert the value into a list. If it was a string the returned list will be a list of characters.
Function sync​_do​_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.
Function sync​_do​_reject Filters a sequence of objects by applying a test to each object, and rejecting the objects with the test succeeding.
Function sync​_do​_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.
Function sync​_do​_select Filters a sequence of objects by applying a test to each object, and only selecting the objects with the test succeeding.
Function sync​_do​_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.
Function sync​_do​_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:
Function sync​_do​_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.
Variable ​_uri​_scheme​_re Undocumented
Variable ​_word​_beginning​_split​_re Undocumented
Variable ​_word​_re Undocumented
F =

Undocumented

Value
t.TypeVar('F',
          bound=t.Callable[..., t.Any])
FILTERS =

Undocumented

Value
{'abs': abs,
 'attr': do_attr,
 'batch': do_batch,
 'capitalize': do_capitalize,
 'center': do_center,
 'count': len,
 'd': do_default,
...
K =

Undocumented

Value
t.TypeVar('K')
V =

Undocumented

Value
t.TypeVar('V')
def _min_or_max(environment, value, func, case_sensitive, attribute):

Undocumented

Parameters
environment:EnvironmentUndocumented
value:t.Iterable[V]Undocumented
func:t.Callable[..., V]Undocumented
case​_sensitive:boolUndocumented
attribute:t.Optional[t.Union[str, int]]Undocumented
Returns
t.Union[V, Undefined]Undocumented
def _prepare_attribute_parts(attr):

Undocumented

Parameters
attr:t.Optional[t.Union[str, int]]Undocumented
Returns
t.List[t.Union[str, int]]Undocumented
async def async_select_or_reject(context, value, args, kwargs, modfunc, lookup_attr):

Undocumented

Parameters
context:ContextUndocumented
value:t.Union[t.AsyncIterable[V], t.Iterable[V]]Undocumented
args:t.TupleUndocumented
kwargs:t.Dict[str, t.Any]Undocumented
modfunc:t.Callable[[t.Any], t.Any]Undocumented
lookup​_attr:boolUndocumented
Returns
t.AsyncIterator[V]Undocumented
def contextfilter(f):

Pass the context as the first argument to the decorated function.

Deprecated since version 3.0: Will be removed in Jinja 3.1. Use ~jinja2.pass_context instead.
Parameters
f:FUndocumented
Returns
FUndocumented
@pass_environment
def do_attr(environment, obj, name):

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 :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details.

Parameters
environment:EnvironmentUndocumented
obj:t.AnyUndocumented
name:strUndocumented
Returns
t.Union[Undefined, t.Any]Undocumented
def do_batch(value, linecount, fill_with=None):

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, '&nbsp;') %}
  <tr>
  {%- for column in row %}
    <td>{{ column }}</td>
  {%- endfor %}
  </tr>
{%- endfor %}
</table>
Parameters
value:t.Iterable[V]Undocumented
linecount:intUndocumented
fill​_with:t.Optional[V]Undocumented
Returns
t.Iterator[t.List[V]]Undocumented
def do_capitalize(s):
Capitalize a value. The first character will be uppercase, all others lowercase.
Parameters
s:strUndocumented
Returns
strUndocumented
def do_center(value, width=80):
Centers the value in a field of a given width.
Parameters
value:strUndocumented
width:intUndocumented
Returns
strUndocumented
def do_default(value, default_value='', boolean=False):

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 ~jinja2.Environment with ~jinja2.ChainableUndefined to make the default filter work on nested elements and attributes that may contain undefined values in the chain without getting an ~jinja2.UndefinedError.
Parameters
value:VUndocumented
default​_value:VUndocumented
boolean:boolUndocumented
Returns
VUndocumented
def do_dictsort(value, case_sensitive=False, by='key', reverse=False):

Sort a dict and yield (key, value) pairs. Python dicts may not be in the order you want to display them in, so sort them first.

{% for key, value in mydict|dictsort %}
    sort the dict by key, case insensitive

{% for key, value in mydict|dictsort(reverse=true) %}
    sort the dict by key, case insensitive, reverse order

{% for key, value in mydict|dictsort(true) %}
    sort the dict by key, case sensitive

{% for key, value in mydict|dictsort(false, 'value') %}
    sort the dict by value, case insensitive
Parameters
value:t.Mapping[K, V]Undocumented
case​_sensitive:boolUndocumented
by:te.Literal['key', 'value']Undocumented
reverse:boolUndocumented
Returns
t.List[t.Tuple[K, V]]Undocumented
def do_filesizeformat(value, binary=False):
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).
Parameters
value:t.Union[str, float, int]Undocumented
binary:boolUndocumented
Returns
strUndocumented
@async_variant(sync_do_first)
async def do_first(environment, seq):

Undocumented

Parameters
environment:EnvironmentUndocumented
seq:t.Union[t.AsyncIterable[V], t.Iterable[V]]Undocumented
Returns
t.Union[V, Undefined]Undocumented
def do_float(value, default=0.0):
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.
Parameters
value:t.AnyUndocumented
default:floatUndocumented
Returns
floatUndocumented
def do_forceescape(value):
Enforce HTML escaping. This will probably double escape variables.
Parameters
value:t.Union[str, HasHTML]Undocumented
Returns
MarkupUndocumented
def do_format(value, *args, **kwargs):

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) }}
Parameters
value:strUndocumented
*args:t.AnyUndocumented
**kwargs:t.AnyUndocumented
Returns
strUndocumented
@async_variant(sync_do_groupby)
async def do_groupby(environment, value, attribute, default=None):

Undocumented

Parameters
environment:EnvironmentUndocumented
value:t.Union[t.AsyncIterable[V], t.Iterable[V]]Undocumented
attribute:t.Union[str, int]Undocumented
default:t.Optional[t.Any]Undocumented
Returns
t.List[t.Tuple[t.Any, t.List[V]]]Undocumented
def do_indent(s, width=4, first=False, blank=False):

Return a copy of the string with each line indented by 4 spaces. The first line and blank lines are not indented by default.

Changed in version 3.0: width can be a string.

Changed in version 2.10: Blank lines are not indented by default.

Rename the indentfirst argument to first.

Parameters
s:strUndocumented
width:t.Union[int, str]Number of spaces, or a string, to indent by.
first:boolDon't skip indenting the first line.
blank:boolDon't skip indenting empty lines.
Returns
strUndocumented
def do_int(value, default=0, base=10):
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.
Parameters
value:t.AnyUndocumented
default:intUndocumented
base:intUndocumented
Returns
intUndocumented
@async_variant(sync_do_join)
async def do_join(eval_ctx, value, d='', attribute=None):

Undocumented

Parameters
eval​_ctx:EvalContextUndocumented
value:t.Union[t.AsyncIterable, t.Iterable]Undocumented
d:strUndocumented
attribute:t.Optional[t.Union[str, int]]Undocumented
Returns
strUndocumented
@pass_environment
def do_last(environment, seq):

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 }}
Parameters
environment:EnvironmentUndocumented
seq:t.Reversible[V]Undocumented
Returns
t.Union[V, Undefined]Undocumented
@async_variant(sync_do_list)
async def do_list(value):

Undocumented

Parameters
value:t.Union[t.AsyncIterable[V], t.Iterable[V]]Undocumented
Returns
t.List[V]Undocumented
def do_lower(s):
Convert a value to lowercase.
Parameters
s:strUndocumented
Returns
strUndocumented
@async_variant(sync_do_map)
async def do_map(context, value, *args, **kwargs):

Undocumented

Parameters
context:ContextUndocumented
value:t.Union[t.AsyncIterable, t.Iterable]Undocumented
*args:t.AnyUndocumented
**kwargs:t.AnyUndocumented
Returns
t.AsyncIterableUndocumented
def do_mark_safe(value):
Mark the value as safe which means that in an environment with automatic escaping enabled this variable will not be escaped.
Parameters
value:strUndocumented
Returns
MarkupUndocumented
def do_mark_unsafe(value):
Mark a value as unsafe. This is the reverse operation for safe.
Parameters
value:strUndocumented
Returns
strUndocumented
@pass_environment
def do_max(environment, value, case_sensitive=False, attribute=None):

Return the largest item from the sequence.

{{ [1, 2, 3]|max }}
    -> 3
Parameters
environment:EnvironmentUndocumented
value:t.Iterable[V]Undocumented
case​_sensitive:boolTreat upper and lower case strings as distinct.
attribute:t.Optional[t.Union[str, int]]Get the object with the max value of this attribute.
Returns
t.Union[V, Undefined]Undocumented
@pass_environment
def do_min(environment, value, case_sensitive=False, attribute=None):

Return the smallest item from the sequence.

{{ [1, 2, 3]|min }}
    -> 1
Parameters
environment:EnvironmentUndocumented
value:t.Iterable[V]Undocumented
case​_sensitive:boolTreat upper and lower case strings as distinct.
attribute:t.Optional[t.Union[str, int]]Get the object with the min value of this attribute.
Returns
t.Union[V, Undefined]Undocumented
def do_pprint(value):
Pretty print a variable. Useful for debugging.
Parameters
value:t.AnyUndocumented
Returns
strUndocumented
@pass_context
def do_random(context, seq):
Return a random item from the sequence.
Parameters
context:ContextUndocumented
seq:t.Sequence[V]Undocumented
Returns
t.Union[V, Undefined]Undocumented
@async_variant(sync_do_reject)
async def do_reject(context, value, *args, **kwargs):

Undocumented

Parameters
context:ContextUndocumented
value:t.Union[t.AsyncIterable[V], t.Iterable[V]]Undocumented
*args:t.AnyUndocumented
**kwargs:t.AnyUndocumented
Returns
t.AsyncIterator[V]Undocumented
@async_variant(sync_do_rejectattr)
async def do_rejectattr(context, value, *args, **kwargs):

Undocumented

Parameters
context:ContextUndocumented
value:t.Union[t.AsyncIterable[V], t.Iterable[V]]Undocumented
*args:t.AnyUndocumented
**kwargs:t.AnyUndocumented
Returns
t.AsyncIterator[V]Undocumented
@pass_eval_context
def do_replace(eval_ctx, s, old, new, count=None):

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
Parameters
eval​_ctx:EvalContextUndocumented
s:strUndocumented
old:strUndocumented
new:strUndocumented
count:t.Optional[int]Undocumented
Returns
strUndocumented
def do_reverse(value):
Reverse the object or return an iterator that iterates over it the other way round.
Parameters
value:t.Union[str, t.Iterable[V]]Undocumented
Returns
t.Union[str, t.Iterable[V]]Undocumented
def do_round(value, precision=0, method='common'):

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
Parameters
value:floatUndocumented
precision:intUndocumented
method:te.Literal['common', 'ceil', 'floor']Undocumented
Returns
floatUndocumented
@async_variant(sync_do_select)
async def do_select(context, value, *args, **kwargs):

Undocumented

Parameters
context:ContextUndocumented
value:t.Union[t.AsyncIterable[V], t.Iterable[V]]Undocumented
*args:t.AnyUndocumented
**kwargs:t.AnyUndocumented
Returns
t.AsyncIterator[V]Undocumented
@async_variant(sync_do_selectattr)
async def do_selectattr(context, value, *args, **kwargs):

Undocumented

Parameters
context:ContextUndocumented
value:t.Union[t.AsyncIterable[V], t.Iterable[V]]Undocumented
*args:t.AnyUndocumented
**kwargs:t.AnyUndocumented
Returns
t.AsyncIterator[V]Undocumented
@async_variant(sync_do_slice)
async def do_slice(value, slices, fill_with=None):

Undocumented

Parameters
value:t.Union[t.AsyncIterable[V], t.Iterable[V]]Undocumented
slices:intUndocumented
fill​_with:t.Optional[t.Any]Undocumented
Returns
t.Iterator[t.List[V]]Undocumented
@pass_environment
def do_sort(environment, value, reverse=False, case_sensitive=False, attribute=None):

Sort an iterable using Python's sorted.

{% for city in cities|sort %}
    ...
{% endfor %}

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.
Parameters
environment:EnvironmentUndocumented
value:t.Iterable[V]Undocumented
reverse:boolSort descending instead of ascending.
case​_sensitive:boolWhen sorting strings, sort upper and lower case separately.
attribute:t.Optional[t.Union[str, int]]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".
Returns
t.List[V]Undocumented
def do_striptags(value):
Strip SGML/XML tags and replace adjacent whitespace by one space.
Parameters
value:t.Union[str, HasHTML]Undocumented
Returns
strUndocumented
@async_variant(sync_do_sum)
async def do_sum(environment, iterable, attribute=None, start=0):

Undocumented

Parameters
environment:EnvironmentUndocumented
iterable:t.Union[t.AsyncIterable[V], t.Iterable[V]]Undocumented
attribute:t.Optional[t.Union[str, int]]Undocumented
start:VUndocumented
Returns
VUndocumented
def do_title(s):
Return a titlecased version of the value. I.e. words will start with uppercase letters, all remaining characters are lowercase.
Parameters
s:strUndocumented
Returns
strUndocumented
@pass_eval_context
def do_tojson(eval_ctx, value, indent=None):

Serialize an object to a string of JSON, and mark it safe to render in HTML. This filter is only for use in HTML documents.

The returned string is safe to render in HTML documents and <script> tags. The exception is in HTML attributes that are double quoted; either use single quotes or the |forceescape filter.

New in version 2.9.
Parameters
eval​_ctx:EvalContextUndocumented
value:t.AnyThe object to serialize to JSON.
indent:t.Optional[int]The indent parameter passed to dumps, for pretty-printing the value.
Returns
MarkupUndocumented
def do_trim(value, chars=None):
Strip leading and trailing characters, by default whitespace.
Parameters
value:strUndocumented
chars:t.Optional[str]Undocumented
Returns
strUndocumented
@pass_environment
def do_truncate(env, s, length=255, killwords=False, end='...', leeway=None):

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.

Parameters
env:EnvironmentUndocumented
s:strUndocumented
length:intUndocumented
killwords:boolUndocumented
end:strUndocumented
leeway:t.Optional[int]Undocumented
Returns
strUndocumented
@pass_environment
def do_unique(environment, value, case_sensitive=False, attribute=None):

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.

Parameters
environment:EnvironmentUndocumented
value:t.Iterable[V]Undocumented
case​_sensitive:boolTreat upper and lower case strings as distinct.
attribute:t.Optional[t.Union[str, int]]Filter objects with unique values for this attribute.
Returns
t.Iterator[V]Undocumented
def do_upper(s):
Convert a value to uppercase.
Parameters
s:strUndocumented
Returns
strUndocumented
def do_urlencode(value):

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.

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.
Parameters
value:t.Union[str, t.Mapping[str, t.Any], t.Iterable[t.Tuple[str, t.Any]]]Data to quote. A string will be quoted directly. A dict or iterable of (key, value) pairs will be joined as a query string.
Returns
strUndocumented
@pass_eval_context
def do_urlize(eval_ctx, value, trim_url_limit=None, nofollow=False, target=None, rel=None, extra_schemes=None):

Convert URLs in text into clickable links.

This may not recognize links in some situations. Usually, a more comprehensive formatter, such as a Markdown library, is a better choice.

Works on http://, https://, www., mailto:, and email addresses. Links with trailing punctuation (periods, commas, closing parentheses) and leading punctuation (opening parentheses) are recognized excluding the punctuation. Email addresses that include header fields are not recognized (for example, mailto:address@example.com?cc=copy@example.com).

Changed in version 3.0: The extra_schemes parameter was added.
Changed in version 3.0: Generate https:// links for URLs without a scheme.
Changed in version 3.0: The parsing rules were updated. Recognize email addresses with or without the mailto: scheme. Validate IP addresses. Ignore parentheses and brackets in more cases.
Changed in version 2.8: The target parameter was added.
Parameters
eval​_ctx:EvalContextUndocumented
value:strOriginal text containing URLs to link.
trim​_url​_limit:t.Optional[int]Shorten displayed URL values to this length.
nofollow:boolAdd the rel=nofollow attribute to links.
target:t.Optional[str]Add the target attribute to links.
rel:t.Optional[str]Add the rel attribute to links.
extra​_schemes:t.Optional[t.Iterable[str]]Recognize URLs that start with these schemes in addition to the default behavior. Defaults to env.policies["urlize.extra_schemes"], which defaults to no extra schemes.
Returns
strUndocumented
def do_wordcount(s):
Count the words in that string.
Parameters
s:strUndocumented
Returns
intUndocumented
@pass_environment
def do_wordwrap(environment, s, width=79, break_long_words=True, wrapstring=None, break_on_hyphens=True):

Wrap a string to the given width. Existing newlines are treated as paragraphs to be wrapped separately.

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.
Parameters
environment:EnvironmentUndocumented
s:strOriginal text to wrap.
width:intMaximum length of wrapped lines.
break​_long​_words:boolIf a word is longer than width, break it across lines.
wrapstring:t.Optional[str]String to join each wrapped line. Defaults to Environment.newline_sequence.
break​_on​_hyphens:boolIf a word contains hyphens, it may be split across lines.
Returns
strUndocumented
@pass_eval_context
def do_xmlattr(eval_ctx, d, autospace=True):

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.

Parameters
eval​_ctx:EvalContextUndocumented
d:t.Mapping[str, t.Any]Undocumented
autospace:boolUndocumented
Returns
strUndocumented
def environmentfilter(f):

Pass the environment as the first argument to the decorated function.

Deprecated since version 3.0: Will be removed in Jinja 3.1. Use ~jinja2.pass_environment instead.
Parameters
f:FUndocumented
Returns
FUndocumented
def evalcontextfilter(f):

Pass the eval context as the first argument to the decorated function.

Deprecated since version 3.0: Will be removed in Jinja 3.1. Use ~jinja2.pass_eval_context instead.
New in version 2.4.
Parameters
f:FUndocumented
Returns
FUndocumented
def ignore_case(value):
For use as a postprocessor for make_attrgetter. Converts strings to lowercase and returns other types as-is.
Parameters
value:VUndocumented
Returns
VUndocumented
def make_attrgetter(environment, attribute, postprocess=None, default=None):
Returns a callable that looks up the given attribute from a passed object with the rules of the environment. Dots are allowed to access attributes of attributes. Integer parts in paths are looked up as integers.
Parameters
environment:EnvironmentUndocumented
attribute:t.Optional[t.Union[str, int]]Undocumented
postprocess:t.Optional[t.Callable[[t.Any], t.Any]]Undocumented
default:t.Optional[t.Any]Undocumented
Returns
t.Callable[[t.Any], t.Any]Undocumented
def make_multi_attrgetter(environment, attribute, postprocess=None):

Returns a callable that looks up the given comma separated attributes from a passed object with the rules of the environment. Dots are allowed to access attributes of each attribute. Integer parts in paths are looked up as integers.

The value returned by the returned callable is a list of extracted attribute values.

Examples of attribute: "attr1,attr2", "attr1.inner1.0,attr2.inner2.0", etc.

Parameters
environment:EnvironmentUndocumented
attribute:t.Optional[t.Union[str, int]]Undocumented
postprocess:t.Optional[t.Callable[[t.Any], t.Any]]Undocumented
Returns
t.Callable[[t.Any], t.List[t.Any]]Undocumented
def prepare_map(context, args, kwargs):

Undocumented

Parameters
context:ContextUndocumented
args:t.TupleUndocumented
kwargs:t.Dict[str, t.Any]Undocumented
Returns
t.Callable[[t.Any], t.Any]Undocumented
def prepare_select_or_reject(context, args, kwargs, modfunc, lookup_attr):

Undocumented

Parameters
context:ContextUndocumented
args:t.TupleUndocumented
kwargs:t.Dict[str, t.Any]Undocumented
modfunc:t.Callable[[t.Any], t.Any]Undocumented
lookup​_attr:boolUndocumented
Returns
t.Callable[[t.Any], t.Any]Undocumented
def select_or_reject(context, value, args, kwargs, modfunc, lookup_attr):

Undocumented

Parameters
context:ContextUndocumented
value:t.Iterable[V]Undocumented
args:t.TupleUndocumented
kwargs:t.Dict[str, t.Any]Undocumented
modfunc:t.Callable[[t.Any], t.Any]Undocumented
lookup​_attr:boolUndocumented
Returns
t.Iterator[V]Undocumented
@pass_environment
def sync_do_first(environment, seq):
Return the first item of a sequence.
Parameters
environment:EnvironmentUndocumented
seq:t.Iterable[V]Undocumented
Returns
t.Union[V, Undefined]Undocumented
@pass_environment
def sync_do_groupby(environment, value, attribute, default=None):

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>

You can specify a default value to use if an object in the list does not have the given attribute.

<ul>{% for city, items in users|groupby("city", default="NY") %}
  <li>{{ city }}: {{ items|map(attribute="name")|join(", ") }}</li>
{% endfor %}</ul>
Changed in version 3.0: Added the default parameter.
Changed in version 2.6: The attribute supports dot notation for nested access.
Parameters
environment:EnvironmentUndocumented
value:t.Iterable[V]Undocumented
attribute:t.Union[str, int]Undocumented
default:t.Optional[t.Any]Undocumented
Returns
t.List[t.Tuple[t.Any, t.List[V]]]Undocumented
@pass_eval_context
def sync_do_join(eval_ctx, value, d='', attribute=None):

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.
Parameters
eval​_ctx:EvalContextUndocumented
value:t.IterableUndocumented
d:strUndocumented
attribute:t.Optional[t.Union[str, int]]Undocumented
Returns
strUndocumented
def sync_do_list(value):
Convert the value into a list. If it was a string the returned list will be a list of characters.
Parameters
value:t.Iterable[V]Undocumented
Returns
t.List[V]Undocumented
@pass_context
def sync_do_map(context, value, *args, **kwargs):

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)
(getattr(u, "username", "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.
Parameters
context:ContextUndocumented
value:t.IterableUndocumented
*args:t.AnyUndocumented
**kwargs:t.AnyUndocumented
Returns
t.IterableUndocumented
@pass_context
def sync_do_reject(context, value, *args, **kwargs):

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.
Parameters
context:ContextUndocumented
value:t.Iterable[V]Undocumented
*args:t.AnyUndocumented
**kwargs:t.AnyUndocumented
Returns
t.Iterator[V]Undocumented
@pass_context
def sync_do_rejectattr(context, value, *args, **kwargs):

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.
Parameters
context:ContextUndocumented
value:t.Iterable[V]Undocumented
*args:t.AnyUndocumented
**kwargs:t.AnyUndocumented
Returns
t.Iterator[V]Undocumented
@pass_context
def sync_do_select(context, value, *args, **kwargs):

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.
Parameters
context:ContextUndocumented
value:t.Iterable[V]Undocumented
*args:t.AnyUndocumented
**kwargs:t.AnyUndocumented
Returns
t.Iterator[V]Undocumented
@pass_context
def sync_do_selectattr(context, value, *args, **kwargs):

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.
Parameters
context:ContextUndocumented
value:t.Iterable[V]Undocumented
*args:t.AnyUndocumented
**kwargs:t.AnyUndocumented
Returns
t.Iterator[V]Undocumented
def sync_do_slice(value, slices, fill_with=None):

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.

Parameters
value:t.Collection[V]Undocumented
slices:intUndocumented
fill​_with:t.Optional[V]Undocumented
Returns
t.Iterator[t.List[V]]Undocumented
@pass_environment
def sync_do_sum(environment, iterable, attribute=None, start=0):

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.
Parameters
environment:EnvironmentUndocumented
iterable:t.Iterable[V]Undocumented
attribute:t.Optional[t.Union[str, int]]Undocumented
start:VUndocumented
Returns
VUndocumented
_uri_scheme_re =

Undocumented

_word_beginning_split_re =

Undocumented

_word_re =

Undocumented