Skip to content

iter (32)

any

any(seq: collections.abc.Iterable[typing.Any], attribute: str | None = None) -> bool

Check if at least one of the item in the sequence evaluates to true.

Example

Jinja call:

{{ [True, False] | any }}
Result: True

DocStrings

Parameters:

Name Type Description Default
seq Iterable[Any]

An iterable object.

required
attribute str | None

The attribute name to use on each object of the iterable.

None
Source code in src/jinjarope/iterfilters.py
281
282
283
284
285
286
287
288
289
290
291
292
def do_any(seq: Iterable[Any], attribute: str | None = None) -> bool:
    """Check if at least one of the item in the sequence evaluates to true.

    The `any` builtin as a filter for Jinja templates.

    Args:
        seq: An iterable object.
        attribute: The attribute name to use on each object of the iterable.
    """
    if attribute is None:
        return any(seq)
    return any(getattr(i, attribute) for i in seq)

batch

batch(value: Iterable[~V], linecount: int, fill_with: Optional[~V] = None) -> Iterator[List[~V]]

A filter that batches items. It works pretty much like slice

Example

Jinja call:

{{ ["a", "b", "c", "d", "e"] | batch(2) | list }}
Result: [['a', 'b'], ['c', 'd'], ['e']]

Example

Jinja call:

{{ ["a", "b", "c"] | batch(2, fill_with="x") | list }}
Result: [['a', 'b'], ['c', 'x']]

DocStrings
Source code in .venv/lib/python3.12/site-packages/jinja2/filters.py
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
def do_batch(
    value: "t.Iterable[V]", linecount: int, fill_with: "t.Optional[V]" = None
) -> "t.Iterator[t.List[V]]":
    """
    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:

    .. sourcecode:: html+jinja

        <table>
        {%- for row in items|batch(3, '&nbsp;') %}
          <tr>
          {%- for column in row %}
            <td>{{ column }}</td>
          {%- endfor %}
          </tr>
        {%- endfor %}
        </table>
    """
    tmp: "t.List[V]" = []

    for item in value:
        if len(tmp) == linecount:
            yield tmp
            tmp = []

        tmp.append(item)

    if tmp:
        if fill_with is not None and len(tmp) < linecount:
            tmp += [fill_with] * (linecount - len(tmp))

        yield tmp

batched

batched(iterable: collections.abc.Iterable[~T], n: int) -> collections.abc.Generator[tuple[~T, ...], None, None]

Batch data into tuples of length n. The last batch may be shorter.

Example

Jinja call:

{% for a, b in range(10) | batched(2) %}
{{ a }}: {{ b }}
{% endfor %}
Result: 0: 1 2: 3 4: 5 6: 7 8: 9

DocStrings

Examples:

batched('ABCDEFG', 3)  # returns ABC DEF G

Parameters:

Name Type Description Default
iterable Iterable[T]

The iterable to yield as batches

required
n int

The batch size

required
Source code in src/jinjarope/iterfilters.py
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
def batched(iterable: Iterable[T], n: int) -> Generator[tuple[T, ...], None, None]:
    """Batch data into tuples of length n. The last batch may be shorter.

    Note: this function was added to Py3.12 itertools

    Examples:
        ``` py
        batched('ABCDEFG', 3)  # returns ABC DEF G
        ```

    Args:
        iterable: The iterable to yield as batches
        n: The batch size
    """
    if n < 1:
        msg = "n must be at least one"
        raise ValueError(msg)
    it = iter(iterable)
    while batch := tuple(itertools.islice(it, n)):
        yield batch

chain

chain(*iterables: collections.abc.Iterable[~T]) -> itertools.chain[~T]

Chain all given iterators.

Example

Jinja call:

{% for val in range(3) | chain(range(5)) %}
{{ val }}
{% endfor %}
Result: 0 1 2 0 1 2 3 4

DocStrings

Examples:

chain('ABC', 'DEF') --> A B C D E F
Source code in src/jinjarope/iterfilters.py
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
def chain(*iterables: Iterable[T]) -> itertools.chain[T]:
    """Chain all given iterators.

    Make an iterator that returns elements from the first iterable until it is
    exhausted, then proceeds to the next iterable, until all of the iterables
    are exhausted. Used for treating consecutive sequences as a single sequence.

    Examples:
        ``` py
        chain('ABC', 'DEF') --> A B C D E F
        ```
    Args:
        iterables: The iterables to chain
    """
    return itertools.chain(*iterables)

combinations

combinations(iterable, r)

Return successive r-length combinations of elements in the iterable.

Example

Jinja call:

{% for val in "ABCD" | combinations(2) %}
{{ val }}
{% endfor %}
Result: ('A', 'B') ('A', 'C') ('A', 'D') ('B', 'C') ('B', 'D') ('C', 'D')

DocStrings

combinations_with_replacement

combinations_with_replacement(iterable, r)

Return successive r-length combinations of elements in the iterable allowing individual elements to have successive repeats.

Example

Jinja call:

{% for val in "ABC" | combinations_with_replacement(2) %}
{{ val }}
{% endfor %}
Result: ('A', 'A') ('A', 'B') ('A', 'C') ('B', 'B') ('B', 'C') ('C', 'C')

DocStrings

compress

compress(data, selectors)

Return data elements corresponding to true selector elements.

Example

Jinja call:

{% for val in "ABCDEF" | compress([1,0,1,0,1,1]) %}
{{ val }}
{% endfor %}
Result: A C E F

DocStrings

first

first(environment: 'Environment', seq: 't.Iterable[V]') -> 't.Union[V, Undefined]'

Return the first item of a sequence.

Example

Jinja call:

{{ [1, 2, 3] | first }}
Result: 1

Example

Jinja call:

{{ "Hello" | first }}
Result: H

DocStrings
Source code in .venv/lib/python3.12/site-packages/jinja2/filters.py
650
651
652
653
654
655
656
657
@async_variant(sync_do_first)  # type: ignore
async def do_first(
    environment: "Environment", seq: "t.Union[t.AsyncIterable[V], t.Iterable[V]]"
) -> "t.Union[V, Undefined]":
    try:
        return await auto_aiter(seq).__anext__()
    except StopAsyncIteration:
        return environment.undefined("No first item, sequence was empty.")

flatten_dict

flatten_dict(dct: collections.abc.Mapping, sep: str = '/', _parent_key: str = '') -> collections.abc.Mapping

Flatten a nested dictionary to a flat one.

Example

Jinja call:

{{ {"a": {"b": {"c": "d"} } } | flatten_dict }}
Result: {'a/b/c': 'd'}

DocStrings

Parameters:

Name Type Description Default
dct Mapping

The dictionary to flatten

required
sep str

The separator to use for joining

'/'
Source code in src/jinjarope/iterfilters.py
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
def flatten_dict(dct: Mapping, sep: str = "/", _parent_key: str = "") -> Mapping:
    """Flatten a nested dictionary to a flat one.

    The individual parts of the "key path" are joined with given separator.

    Args:
        dct: The dictionary to flatten
        sep: The separator to use for joining
    """
    items: list[tuple[str, str]] = []
    for k, v in dct.items():
        new_key = _parent_key + sep + k if _parent_key else k
        if isinstance(v, Mapping):
            flattened = flatten_dict(v, _parent_key=new_key, sep=sep)
            items.extend(flattened.items())
        else:
            items.append((new_key, v))
    return dict(items)

groupby

groupby(environment: 'Environment', value: 't.Iterable[V]', attribute: Union[str, int], default: Optional[Any] = None, case_sensitive: bool = False) -> 't.List[_GroupTuple]'

Group a sequence of objects by an attribute using Python's

Example

Jinja call:

{{ [cycler] | groupby("__module__") }}
Result: [('jinja2.utils', [<class 'jinja2.utils.Cycler'>])]

Example

Jinja call:

{{ [{"name": "A", "type": 1}, {"name": "B", "type": 1}, {"name": "C", "type": 2}] | groupby("type") | list }}
Result: [(1, [{'name': 'A', 'type': 1}, {'name': 'B', 'type': 1}]), (2, [{'name': 'C', 'type': 2}])]

DocStrings
Source code in .venv/lib/python3.12/site-packages/jinja2/filters.py
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
@async_variant(sync_do_groupby)  # type: ignore
async def do_groupby(
    environment: "Environment",
    value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
    attribute: t.Union[str, int],
    default: t.Optional[t.Any] = None,
    case_sensitive: bool = False,
) -> "t.List[_GroupTuple]":
    expr = make_attrgetter(
        environment,
        attribute,
        postprocess=ignore_case if not case_sensitive else None,
        default=default,
    )
    out = [
        _GroupTuple(key, await auto_to_list(values))
        for key, values in groupby(sorted(await auto_to_list(value), key=expr), expr)
    ]

    if not case_sensitive:
        # Return the real key from the first value instead of the lowercase key.
        output_expr = make_attrgetter(environment, attribute, default=default)
        out = [_GroupTuple(output_expr(values[0]), values) for _, values in out]

    return out

groupby_first_letter

groupby_first_letter(data: collections.abc.Iterable[~T], keyfunc: collections.abc.Callable[..., typing.Any] | None = None) -> dict[str, list[~T]]

Group given iterable by first letter.

Example

Jinja call:

{{ ["apple", "banana", "cherry", "avocado", "carrot", "blueberry"] | groupby_first_letter }}
Result: {'A': ['apple', 'avocado'], 'B': ['banana', 'blueberry'], 'C': ['carrot', 'cherry']}

DocStrings

Parameters:

Name Type Description Default
data Iterable[T]

Iterable to group

required
keyfunc Callable[..., Any] | None

Optional alternative sort function

None
Source code in src/jinjarope/iterfilters.py
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
def groupby_first_letter(
    data: Iterable[T],
    keyfunc: Callable[..., Any] | None = None,
) -> dict[str, list[T]]:
    """Group given iterable by first letter.

    Args:
        data: Iterable to group
        keyfunc: Optional alternative sort function
    """
    data = sorted(data, key=keyfunc or (lambda x: x))

    def first_letter(x: Any) -> Any:
        return keyfunc(x)[0].upper() if keyfunc else x[0].upper()

    return {k.upper(): list(g) for k, g in itertools.groupby(data, first_letter)}

groupby_plus

groupby_plus(data: collections.abc.Iterable[~T], key: collections.abc.Callable[[~T], typing.Any] | str | None = None, *, sort_groups: bool = True, natural_sort: bool = False, reverse: bool = False) -> dict[str, list[~T]]

Group given iterable using given group function.

Example

Jinja call:

{{ ["20", "20", "100", "0"] | groupby_plus(natural_sort=True) }}
Result: {'0': ['0'], '20': ['20', '20'], '100': ['100']}

DocStrings

Parameters:

Name Type Description Default
data Iterable[T]

Iterable to group

required
key Callable[[T], Any] | str | None

Sort function or attribute name to use for sorting

None
sort_groups bool

Whether to sort the groups

True
natural_sort bool

Whether to use a natural sort algorithm

False
reverse bool

Whether to reverse the value list

False
Source code in src/jinjarope/iterfilters.py
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
def groupby(
    data: Iterable[T],
    key: Callable[[T], Any] | str | None = None,
    *,
    sort_groups: bool = True,
    natural_sort: bool = False,
    reverse: bool = False,
) -> dict[str, list[T]]:
    """Group given iterable using given group function.

    Args:
        data: Iterable to group
        key: Sort function or attribute name to use for sorting
        sort_groups: Whether to sort the groups
        natural_sort: Whether to use a natural sort algorithm
        reverse: Whether to reverse the value list
    """
    if key is None:

        def keyfunc(x):
            return x

    elif isinstance(key, str):
        keyfunc = operator.attrgetter(key)
    else:
        keyfunc = key
    if sort_groups or natural_sort:
        if natural_sort:
            import natsort

            data = natsort.natsorted(data, key=keyfunc)
        else:
            data = sorted(data, key=keyfunc)
    if reverse:
        data = reversed(list(data))
    return {k: list(g) for k, g in itertools.groupby(data, keyfunc)}

islice

islice(iterable: 'Iterable[T]', *args: 'int | None') -> 'itertools.islice[T]'

Make an iterator that returns selected elements from the iterable.

Example

Jinja call:

{% for val in "ABCDEFG" | islice(2) %}
{{ val }}
{% endfor %}
Result: A B

DocStrings

Examples:

islice('ABCDEFG', 2) --> A B
islice('ABCDEFG', 2, 4) --> C D
islice('ABCDEFG', 2, None) --> C D E F G
islice('ABCDEFG', 0, None, 2) --> A C E G

Parameters:

Name Type Description Default
iterable Iterable[T]

Iterable to slice

required
args int | None

Arguments passed to itertools.islice

()
Source code in src/jinjarope/iterfilters.py
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
def islice(iterable: Iterable[T], *args: int | None) -> itertools.islice[T]:
    """Make an iterator that returns selected elements from the iterable.

    If start is non-zero, then elements from the iterable are skipped until start
    is reached. Afterward, elements are returned consecutively unless step is set
    higher than one which results in items being skipped. If stop is None,
    then iteration continues until the iterator is exhausted, if at all;
    otherwise, it stops at the specified position.

    If start is None, then iteration starts at zero. If step is None,
    then the step defaults to one.

    Unlike regular slicing, islice() does not support negative values
    for start, stop, or step. Can be used to extract related fields from data
    where the internal structure has been flattened (for example, a multi-line report
    may list a name field on every third line).

    Examples:
        ``` py
        islice('ABCDEFG', 2) --> A B
        islice('ABCDEFG', 2, 4) --> C D
        islice('ABCDEFG', 2, None) --> C D E F G
        islice('ABCDEFG', 0, None, 2) --> A C E G
        ```

    Args:
        iterable: Iterable to slice
        args: Arguments passed to itertools.islice
    """
    return itertools.islice(iterable, *args)

join

join(eval_ctx: 'EvalContext', value: Iterable[Any], d: str = '', attribute: Union[str, int, NoneType] = None) -> str

Return a string which is the concatenation of the strings in the

Example

Jinja call:

{{ ["a", "b", "c"] | join }}
Result: abc

Example

Jinja call:

{{ ["a", "b", "c"] | join(" | ") }}
Result: a | b | c

DocStrings
Source code in .venv/lib/python3.12/site-packages/jinja2/filters.py
624
625
626
627
628
629
630
631
@async_variant(sync_do_join)  # type: ignore
async def do_join(
    eval_ctx: "EvalContext",
    value: t.Union[t.AsyncIterable[t.Any], t.Iterable[t.Any]],
    d: str = "",
    attribute: t.Optional[t.Union[str, int]] = None,
) -> str:
    return sync_do_join(eval_ctx, await auto_to_list(value), d, attribute)

last

last(environment: 'Environment', seq: 't.Reversible[V]') -> 't.Union[V, Undefined]'

Return the last item of a sequence.

Example

Jinja call:

{{ ["a", "b", "c"] | last }}
Result: c

DocStrings
Source code in .venv/lib/python3.12/site-packages/jinja2/filters.py
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
@pass_environment
def do_last(
    environment: "Environment", seq: "t.Reversible[V]"
) -> "t.Union[V, Undefined]":
    """Return the last item of a sequence.

    Note: Does not work with generators. You may want to explicitly
    convert it to a list:

    .. sourcecode:: jinja

        {{ data | selectattr('name', '==', 'Jinja') | list | last }}
    """
    try:
        return next(iter(reversed(seq)))
    except StopIteration:
        return environment.undefined("No last item, sequence was empty.")

length

length(obj, /)

Return the number of items in a container.

Aliases: count

Example

Jinja call:

{{ ["a", "b", "c"] | length }}
Result: 3

Example

Jinja call:

{{ "Hello World" | length }}
Result: 11

DocStrings

natsort

natsort(val: collections.abc.Iterable[~T], key: str | collections.abc.Callable[[~T], typing.Any] | None = None, reverse: bool = False, ignore_case: bool = True) -> collections.abc.Iterable[~T]

Using the natsort package, sort a list naturally.

Required packages: natsort

Example

Jinja call:

{{ ["A1", "B1", "A2", "A10"] | natsort }}
Result: ['A1', 'A2', 'A10', 'B1']

DocStrings

Parameters:

Name Type Description Default
val Iterable[T]

the iterable to sort

required
key str | Callable[[T], Any] | None

If str, sort by attribute with given name. If callable, use it as keygetter. If None, sort by objects itself

None
reverse bool

Whether to reverse the sort order

False
ignore_case bool

Whether to ignore case for sorting

True
Source code in src/jinjarope/iterfilters.py
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
def natsort(
    val: Iterable[T],
    key: str | Callable[[T], Any] | None = None,
    reverse: bool = False,
    ignore_case: bool = True,
) -> Iterable[T]:
    """Using the natsort package, sort a list naturally.

    i.e. A1, B1, A2, A10 will sort A1, A2, A10, B1.

    Args:
        val: the iterable to sort
        key: If str, sort by attribute with given name. If callable, use it as keygetter.
             If None, sort by objects itself
        reverse: Whether to reverse the sort order
        ignore_case: Whether to ignore case for sorting
    """
    from natsort import natsorted, ns

    alg = ns.IGNORECASE
    if not ignore_case:
        alg = ns.LOWERCASEFIRST
    key_fn = operator.attrgetter(key) if isinstance(key, str) else key
    return natsorted(val, key=key_fn, reverse=reverse, alg=alg)

pairwise

pairwise(items: 'Iterable[T]') -> 'itertools.pairwise[tuple[T, T]]'

Return an iterator of overlapping pairs taken from the input iterator.

Example

Jinja call:

{% for a, b in [1, 2, 3, 4] | pairwise %}
{{ a }}: {{ b }}
{% endfor %}
Result: 1: 2 2: 3 3: 4

DocStrings

Parameters:

Name Type Description Default
items Iterable[T]

The items to iter pair-wise

required
Source code in src/jinjarope/iterfilters.py
12
13
14
15
16
17
18
19
20
def pairwise(items: Iterable[T]) -> itertools.pairwise[tuple[T, T]]:
    """Return an iterator of overlapping pairs taken from the input iterator.

    s -> (s0,s1), (s1,s2), (s2, s3), ...

    Args:
        items: The items to iter pair-wise
    """
    return itertools.pairwise(items)

permutations

permutations(iterable, r=None)

Return successive r-length permutations of elements in the iterable.

Example

Jinja call:

{% for val in "ABCD" | permutations(2) %}
{{ val }}
{% endfor %}
Result: ('A', 'B') ('A', 'C') ('A', 'D') ('B', 'A') ('B', 'C') ('B', 'D') ('C', 'A') ('C', 'B') ('C', 'D') ('D', 'A') ('D', 'B') ('D', 'C')

DocStrings

product

product(*iterables: 'Iterable[Any]', repeat: 'int' = 1) -> 'itertools.product[tuple[Any, ...]]'

Cartesian product of input iterables.

Example

Jinja call:

{% for val in "ABCD" | product("xy") %}
{{ val }}
{% endfor %}
Result: ('A', 'x') ('A', 'y') ('B', 'x') ('B', 'y') ('C', 'x') ('C', 'y') ('D', 'x') ('D', 'y')

DocStrings

Examples:

product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111

Parameters:

Name Type Description Default
iterables Iterable[Any]

The iterables to create a cartesian product from

()
repeat int

The amount of repititions

1
Source code in src/jinjarope/iterfilters.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
def product(
    *iterables: Iterable[Any],
    repeat: int = 1,
) -> itertools.product[tuple[Any, ...]]:
    """Cartesian product of input iterables.

    Roughly equivalent to nested for-loops in a generator expression.
    For example, product(A, B) returns the same as ((x,y) for x in A for y in B).

    The nested loops cycle like an odometer with the rightmost element advancing
    on every iteration. This pattern creates a lexicographic ordering so that if
    the input's iterables are sorted, the product tuples are emitted in sorted order.

    To compute the product of an iterable with itself, specify the number of repetitions
    with the optional repeat keyword argument. For example, product(A, repeat=4)
    means the same as product(A, A, A, A).

    Examples:
        ``` py
        product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
        product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
        ```

    Args:
        iterables: The iterables to create a cartesian product from
        repeat: The amount of repititions
    """
    return itertools.product(*iterables, repeat=repeat)

reduce_list

reduce_list(items: collections.abc.Iterable[~T]) -> list[~T]

Reduce duplicate items in a list and preserve order.

Example

Jinja call:

{{ ["1", "2", "3", "1"] | reduce_list }}
Result: ['1', '2', '3']

DocStrings

Parameters:

Name Type Description Default
items Iterable[T]

The iterable to recude to a unique-item list

required
Source code in src/jinjarope/iterfilters.py
148
149
150
151
152
153
154
def reduce_list(items: Iterable[T]) -> list[T]:
    """Reduce duplicate items in a list and preserve order.

    Args:
        items: The iterable to recude to a unique-item list
    """
    return list(dict.fromkeys(items))

reject

reject(context: 'Context', value: 't.Iterable[V]', *args: Any, **kwargs: Any) -> 't.Iterator[V]'

Filters a sequence of objects by applying a test to each object,

Example

Jinja call:

{{ [1, 2, 3, 4] | reject("even") | list }}
Result: [1, 3]

DocStrings
Source code in .venv/lib/python3.12/site-packages/jinja2/filters.py
1600
1601
1602
1603
1604
1605
1606
1607
@async_variant(sync_do_reject)  # type: ignore
async def do_reject(
    context: "Context",
    value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
    *args: t.Any,
    **kwargs: t.Any,
) -> "t.AsyncIterator[V]":
    return async_select_or_reject(context, value, args, kwargs, lambda x: not x, False)

rejectattr

rejectattr(context: 'Context', value: 't.Iterable[V]', *args: Any, **kwargs: Any) -> 't.Iterator[V]'

Filters a sequence of objects by applying a test to the specified

DocStrings
Source code in .venv/lib/python3.12/site-packages/jinja2/filters.py
1678
1679
1680
1681
1682
1683
1684
1685
@async_variant(sync_do_rejectattr)  # type: ignore
async def do_rejectattr(
    context: "Context",
    value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
    *args: t.Any,
    **kwargs: t.Any,
) -> "t.AsyncIterator[V]":
    return async_select_or_reject(context, value, args, kwargs, lambda x: not x, True)

repeat

repeat(obj: ~T, times: int | None = None) -> collections.abc.Iterable[~T]

Make an iterator that returns object over and over again.

Example

Jinja call:

{% for val in "ABCD" | repeat(2) %}
{{ val }}
{% endfor %}
Result: ABCD ABCD

DocStrings

Examples:

repeat(10, 3) --> 10 10 10

Parameters:

Name Type Description Default
obj T

The object to return over and over again

required
times int | None

The amount of times to return the object (None means infinite)

None
Source code in src/jinjarope/iterfilters.py
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
def repeat(obj: T, times: int | None = None) -> Iterable[T]:
    """Make an iterator that returns object over and over again.

    Runs indefinitely unless the times argument is specified.

    Examples:
        ``` py
        repeat(10, 3) --> 10 10 10
        ```

    Args:
        obj: The object to return over and over again
        times: The amount of times to return the object (None means infinite)
    """
    if times:
        return itertools.repeat(obj, times=times)
    return itertools.repeat(obj)

reverse

reverse(value: Union[str, Iterable[~V]]) -> Union[str, Iterable[~V]]

Reverse the object or return an iterator that iterates over it the other

Example

Jinja call:

{{ [1, 2, 3] | reverse }}
Result: <list_reverseiterator object at 0x7f827f335630>

Example

Jinja call:

{{ "hello" | list | reverse | join }}
Result: olleh

DocStrings
Source code in .venv/lib/python3.12/site-packages/jinja2/filters.py
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
def do_reverse(value: t.Union[str, t.Iterable[V]]) -> t.Union[str, t.Iterable[V]]:
    """Reverse the object or return an iterator that iterates over it the other
    way round.
    """
    if isinstance(value, str):
        return value[::-1]

    try:
        return reversed(value)  # type: ignore
    except TypeError:
        try:
            rv = list(value)
            rv.reverse()
            return rv
        except TypeError as e:
            raise FilterArgumentError("argument must be iterable") from e

select

select(context: 'Context', value: 't.Iterable[V]', *args: Any, **kwargs: Any) -> 't.Iterator[V]'

Filters a sequence of objects by applying a test to each object,

Example

Jinja call:

{{ [1, 2, 3, 4] | select("even") | list }}
Result: [2, 4]

DocStrings
Source code in .venv/lib/python3.12/site-packages/jinja2/filters.py
1564
1565
1566
1567
1568
1569
1570
1571
@async_variant(sync_do_select)  # type: ignore
async def do_select(
    context: "Context",
    value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
    *args: t.Any,
    **kwargs: t.Any,
) -> "t.AsyncIterator[V]":
    return async_select_or_reject(context, value, args, kwargs, lambda x: x, False)

selectattr

selectattr(context: 'Context', value: 't.Iterable[V]', *args: Any, **kwargs: Any) -> 't.Iterator[V]'

Filters a sequence of objects by applying a test to the specified

DocStrings
Source code in .venv/lib/python3.12/site-packages/jinja2/filters.py
1640
1641
1642
1643
1644
1645
1646
1647
@async_variant(sync_do_selectattr)  # type: ignore
async def do_selectattr(
    context: "Context",
    value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
    *args: t.Any,
    **kwargs: t.Any,
) -> "t.AsyncIterator[V]":
    return async_select_or_reject(context, value, args, kwargs, lambda x: x, True)

slice

slice(value: Collection[~V], slices: int, fill_with: Optional[~V] = None) -> Iterator[List[~V]]

Slice an iterator and return a list of lists containing

Example

Jinja call:

{{ [1, 2, 3, 4, 5] | slice(2) | list }}
Result: [[1, 2, 3], [4, 5]]

DocStrings
Source code in .venv/lib/python3.12/site-packages/jinja2/filters.py
1089
1090
1091
1092
1093
1094
1095
@async_variant(sync_do_slice)  # type: ignore
async def do_slice(
    value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
    slices: int,
    fill_with: t.Optional[t.Any] = None,
) -> "t.Iterator[t.List[V]]":
    return sync_do_slice(await auto_to_list(value), slices, fill_with)

sort

sort(environment: 'Environment', value: 't.Iterable[V]', reverse: bool = False, case_sensitive: bool = False, attribute: Union[str, int, NoneType] = None) -> 't.List[V]'

Sort an iterable using Python's :func:sorted.

Example

Jinja call:

{{ ["c", "b", "a"] | sort }}
Result: ['a', 'b', 'c']

DocStrings
Source code in .venv/lib/python3.12/site-packages/jinja2/filters.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
@pass_environment
def do_sort(
    environment: "Environment",
    value: "t.Iterable[V]",
    reverse: bool = False,
    case_sensitive: bool = False,
    attribute: t.Optional[t.Union[str, int]] = None,
) -> "t.List[V]":
    """Sort an iterable using Python's :func:`sorted`.

    .. sourcecode:: jinja

        {% 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.

    .. sourcecode:: jinja

        {% 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.

    .. sourcecode:: jinja

        {% for user in users|sort(attribute="age,name") %}
            ...
        {% endfor %}

    .. versionchanged:: 2.11.0
        The ``attribute`` parameter can be a comma separated list of
        attributes, e.g. ``"age,name"``.

    .. versionchanged:: 2.6
       The ``attribute`` parameter was added.
    """
    key_func = make_multi_attrgetter(
        environment, attribute, postprocess=ignore_case if not case_sensitive else None
    )
    return sorted(value, key=key_func, reverse=reverse)

unique

unique(environment: 'Environment', value: 't.Iterable[V]', case_sensitive: bool = False, attribute: Union[str, int, NoneType] = None) -> 't.Iterator[V]'

Returns a list of unique items from the given iterable.

Example

Jinja call:

{{ [1, 2, 1] | unique }}
Result: <generator object do_unique at 0x7f82804db9a0>

DocStrings
Source code in .venv/lib/python3.12/site-packages/jinja2/filters.py
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
@pass_environment
def do_unique(
    environment: "Environment",
    value: "t.Iterable[V]",
    case_sensitive: bool = False,
    attribute: t.Optional[t.Union[str, int]] = None,
) -> "t.Iterator[V]":
    """Returns a list of unique items from the given iterable.

    .. sourcecode:: jinja

        {{ ['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.
    """
    getter = make_attrgetter(
        environment, attribute, postprocess=ignore_case if not case_sensitive else None
    )
    seen = set()

    for item in value:
        key = getter(item)

        if key not in seen:
            seen.add(key)
            yield item

zip

zip(*items: 'Iterable[T]') -> 'zip[tuple[T, ...]]'

Zip iterables into a single one.

Example

Jinja call:

{% for a, b in [1, 2] | zip([3, 4]) %}
{{ a }}: {{ b }}
{% endfor %}
Result: 1: 3 2: 4

DocStrings

Parameters:

Name Type Description Default
items Iterable[T]

The iterables to zip

()
Source code in src/jinjarope/iterfilters.py
139
140
141
142
143
144
145
def do_zip(*items: Iterable[T]) -> zip[tuple[T, ...]]:
    """Zip iterables into a single one.

    Args:
        items: The iterables to zip
    """
    return zip(*items)

zip_longest

zip_longest(*iterables: collections.abc.Iterable[typing.Any], fillvalue: Any = None) -> collections.abc.Iterable[typing.Any]

Make an iterator that aggregates elements from each of the iterables.

Example

Jinja call:

{% for val in "ABCD" | zip_longest("xy", fillvalue="-") %}
{{ val }}
{% endfor %}
Result: ('A', 'x', '-') ('B', 'y', None) ('C', None, None) ('D', None, None)

DocStrings

Examples:

zip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-

Parameters:

Name Type Description Default
iterables Iterable[Any]

The iterables to zip

()
fillvalue Any

value to use for filling in case the iterables are of uneven length

None
Source code in src/jinjarope/iterfilters.py
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
def zip_longest(*iterables: Iterable[Any], fillvalue: Any = None) -> Iterable[Any]:
    """Make an iterator that aggregates elements from each of the iterables.

    If the iterables are of uneven length, missing values are filled-in with fillvalue.
    Iteration continues until the longest iterable is exhausted.

    Examples:
        ``` py
        zip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
        ```

    Args:
        iterables: The iterables to zip
        fillvalue: value to use for filling in case the iterables are of uneven length
    """
    return itertools.zip_longest(*iterables, fillvalue)