Skip to content

builtin (4)

cycler

cycler(*items: Any) -> None

Cycle through values by yield them one at a time, then restarting

Example

Jinja call:

{% set row_class = cycler("odd", "even") %}
{{ row_class.next() }}
{{ row_class.next() }}
{{ row_class.next() }}
{{ row_class.current }}
Result: odd even odd even

DocStrings
Source code in .venv/lib/python3.12/site-packages/jinja2/utils.py
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
class Cycler:
    """Cycle through values by yield them one at a time, then restarting
    once the end is reached. Available as ``cycler`` in templates.

    Similar to ``loop.cycle``, but can be used outside loops or across
    multiple loops. For example, render a list of folders and files in a
    list, alternating giving them "odd" and "even" classes.

    .. code-block:: html+jinja

        {% set row_class = cycler("odd", "even") %}
        <ul class="browser">
        {% for folder in folders %}
          <li class="folder {{ row_class.next() }}">{{ folder }}
        {% endfor %}
        {% for file in files %}
          <li class="file {{ row_class.next() }}">{{ file }}
        {% endfor %}
        </ul>

    :param items: Each positional argument will be yielded in the order
        given for each cycle.

    .. versionadded:: 2.1
    """

    def __init__(self, *items: t.Any) -> None:
        if not items:
            raise RuntimeError("at least one item has to be provided")
        self.items = items
        self.pos = 0

    def reset(self) -> None:
        """Resets the current item to the first item."""
        self.pos = 0

    @property
    def current(self) -> t.Any:
        """Return the current item. Equivalent to the item that will be
        returned next time :meth:`next` is called.
        """
        return self.items[self.pos]

    def next(self) -> t.Any:
        """Return the current item, then advance :attr:`current` to the
        next item.
        """
        rv = self.current
        self.pos = (self.pos + 1) % len(self.items)
        return rv

    __next__ = next

current property

current: Any

next

next() -> Any
Source code in .venv/lib/python3.12/site-packages/jinja2/utils.py
720
721
722
723
724
725
726
def next(self) -> t.Any:
    """Return the current item, then advance :attr:`current` to the
    next item.
    """
    rv = self.current
    self.pos = (self.pos + 1) % len(self.items)
    return rv

reset

reset() -> None
Source code in .venv/lib/python3.12/site-packages/jinja2/utils.py
709
710
711
def reset(self) -> None:
    """Resets the current item to the first item."""
    self.pos = 0

joiner

joiner(sep: str = ', ') -> None

A joining helper for templates.

Example

Jinja call:

{% set pipe = joiner("|") %}
"AB"
{{ pipe() }}
"AB"
{{ pipe() }}
"AB"
{{ pipe() }}
Result: `"AB"

"AB" | "AB" |`

DocStrings
Source code in .venv/lib/python3.12/site-packages/jinja2/utils.py
731
732
733
734
735
736
737
738
739
740
741
742
class Joiner:
    """A joining helper for templates."""

    def __init__(self, sep: str = ", ") -> None:
        self.sep = sep
        self.used = False

    def __call__(self) -> str:
        if not self.used:
            self.used = True
            return ""
        return self.sep

lipsum

lipsum(n: int = 5, html: bool = True, min: int = 20, max: int = 100) -> str

Generate some lorem ipsum for the template.

Example

Jinja call:

{{ lipsum() }}
Result: <p>Nonummy tellus bibendum suscipit habitant tortor, taciti cubilia blandit felis blandit, integer tincidunt id dictum vestibulum, ac amet ligula suspendisse. Massa id dolor luctus commodo, ultrices primis torquent feugiat condimentum, vehicula ornare diam dictum rhoncus consectetuer cursus vehicula,. Est dapibus auctor ante, tincidunt adipiscing sociis mollis integer at, aptent tincidunt ridiculus nascetur aliquam neque lacinia, vel suscipit. Elit phasellus orci dolor, nostra risus ultricies fusce at facilisi, phasellus imperdiet dolor lacus, semper rhoncus senectus habitasse nascetur, nibh parturient litora. Orci nostra varius fringilla quis, nisl ullamcorper tempus nisi venenatis.</p> <p>Dictum platea cursus pellentesque sagittis justo senectus morbi vestibulum, montes vestibulum primis per penatibus, orci in tincidunt tristique parturient, faucibus. Non fusce curae vivamus accumsan, laoreet lacinia aliquet nonummy potenti, cubilia vestibulum pulvinar nostra cursus vehicula, faucibus cras ligula arcu fermentum. Scelerisque cubilia luctus sed posuere, ligula gravida mi amet duis, arcu sodales odio quam hac, tristique phasellus neque sodales. Proin senectus ultrices sem quis, dis velit diam urna fringilla condimentum, ultricies faucibus massa nec posuere ridiculus. Sapien magna cum torquent cum vulputate, inceptos mattis egestas ornare primis, iaculis.</p> <p>Conubia luctus tristique vehicula nullam lobortis amet, accumsan turpis vitae nonummy ipsum sed, a tempus phasellus aenean suspendisse, ridiculus egestas dignissim diam ultricies. Commodo lorem quam laoreet tempus ultricies, luctus nec duis cras senectus, dictum consectetuer phasellus gravida, vel potenti dictumst a. Ornare proin class netus, id eget phasellus consequat, semper torquent metus praesent, ante ut elit accumsan ridiculus penatibus diam, ipsum eros cras habitasse purus posuere velit,. Suspendisse erat etiam nascetur facilisis, hendrerit sit viverra ullamcorper iaculis adipiscing, mauris platea pulvinar praesent, nisl egestas commodo.</p> <p>Sociosqu habitasse pretium malesuada aliquet semper pharetra, sociosqu libero leo odio ut fusce lectus, aliquam semper malesuada aptent vestibulum, massa eget interdum rhoncus, placerat. Adipiscing mattis nulla felis dictumst tristique, rutrum laoreet egestas lorem facilisi luctus.</p> <p>Inceptos turpis congue vehicula hac ac, posuere lacus tincidunt cum in tempus, urna enim volutpat elit, congue parturient nunc mus venenatis porta. Lobortis habitasse semper diam a volutpat, massa laoreet luctus vel dapibus, fames nisl sodales interdum, nulla tellus hymenaeos sociosqu felis. Cum in eu quam justo pede velit, tortor nisl tellus lectus bibendum adipiscing fringilla, massa.</p>

DocStrings
Source code in .venv/lib/python3.12/site-packages/jinja2/utils.py
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
def generate_lorem_ipsum(
    n: int = 5, html: bool = True, min: int = 20, max: int = 100
) -> str:
    """Generate some lorem ipsum for the template."""
    from .constants import LOREM_IPSUM_WORDS

    words = LOREM_IPSUM_WORDS.split()
    result = []

    for _ in range(n):
        next_capitalized = True
        last_comma = last_fullstop = 0
        word = None
        last = None
        p = []

        # each paragraph contains out of 20 to 100 words.
        for idx, _ in enumerate(range(randrange(min, max))):
            while True:
                word = choice(words)
                if word != last:
                    last = word
                    break
            if next_capitalized:
                word = word.capitalize()
                next_capitalized = False
            # add commas
            if idx - randrange(3, 8) > last_comma:
                last_comma = idx
                last_fullstop += 2
                word += ","
            # add end of sentences
            if idx - randrange(10, 20) > last_fullstop:
                last_comma = last_fullstop = idx
                word += "."
                next_capitalized = True
            p.append(word)

        # ensure that the paragraph ends with a dot.
        p_str = " ".join(p)

        if p_str.endswith(","):
            p_str = p_str[:-1] + "."
        elif not p_str.endswith("."):
            p_str += "."

        result.append(p_str)

    if not html:
        return "\n\n".join(result)
    return markupsafe.Markup(
        "\n".join(f"<p>{markupsafe.escape(x)}</p>" for x in result)
    )

namespace

namespace(*args: Any, **kwargs: Any) -> None

A namespace object that can hold arbitrary attributes. It may be

Example

Jinja call:

{% set ns = namespace() %}
{% set ns.foo = 'bar' %}
{{ ns.foo }}
Result: bar

DocStrings
Source code in .venv/lib/python3.12/site-packages/jinja2/utils.py
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
class Namespace:
    """A namespace object that can hold arbitrary attributes.  It may be
    initialized from a dictionary or with keyword arguments."""

    def __init__(*args: t.Any, **kwargs: t.Any) -> None:  # noqa: B902
        self, args = args[0], args[1:]
        self.__attrs = dict(*args, **kwargs)

    def __getattribute__(self, name: str) -> t.Any:
        # __class__ is needed for the awaitable check in async mode
        if name in {"_Namespace__attrs", "__class__"}:
            return object.__getattribute__(self, name)
        try:
            return self.__attrs[name]
        except KeyError:
            raise AttributeError(name) from None

    def __setitem__(self, name: str, value: t.Any) -> None:
        self.__attrs[name] = value

    def __repr__(self) -> str:
        return f"<Namespace {self.__attrs!r}>"