Skip to content

misc (14)

add

add(text: str | None, prefix: str = '', suffix: str = '') -> str

Add a pre- or suffix to a value if the value is true-ish.

Example

Jinja call:

{{ "a" | add("b", "c") }}
Result: bac

DocStrings

Parameters:

Name Type Description Default
text str | None

The text to check

required
prefix str

Prefix to add if text is true-ish

''
suffix str

Suffix to add if text is true-ish

''
Source code in src/jinjarope/envglobals.py
68
69
70
71
72
73
74
75
76
def add(text: str | None, prefix: str = "", suffix: str = "") -> str:
    """Add a pre- or suffix to a value if the value is true-ish.

    Args:
        text: The text to check
        prefix: Prefix to add if text is true-ish
        suffix: Suffix to add if text is true-ish
    """
    return f"{prefix}{text}{suffix}" if text else ""

attr

attr(environment: 'Environment', obj: Any, name: str) -> Union[jinja2.runtime.Undefined, Any]

Get an attribute of an object. foo|attr("bar") works like

Example

Jinja call:

{{ "abc" | attr("removesuffix") }}
Result: <built-in method removesuffix of str object at 0x7f34ffbd9bf0>

Example

Jinja call:

{{ ["abc", "def"] | map(attribute="upper") | list }}
Result: [<built-in method upper of str object at 0x7f351abe3e60>, <built-in method upper of str object at 0x7f3519d87b40>]

DocStrings
Source code in .venv/lib/python3.12/site-packages/jinja2/filters.py
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
@pass_environment
def do_attr(
    environment: "Environment", obj: t.Any, name: str
) -> t.Union[Undefined, t.Any]:
    """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.
    """
    try:
        name = str(name)
    except UnicodeError:
        pass
    else:
        try:
            value = getattr(obj, name)
        except AttributeError:
            pass
        else:
            if environment.sandboxed:
                environment = t.cast("SandboxedEnvironment", environment)

                if not environment.is_safe_attribute(obj, name, value):
                    return environment.unsafe_undefined(obj, name)

            return value

    return environment.undefined(obj=obj, name=name)

check_output

check_output(call: 'str | Sequence[str]', cwd: 'str | os.PathLike[str] | None' = None, use_cache: 'bool' = False) -> 'str | None'

Execute a system call and return its output as a string.

Example

Jinja call:

{{ "dir" | check_output }}
Result: LICENSE docs mkdocs.yml pyproject.toml tests README.md duties.py overrides src uv.lock

DocStrings

Parameters:

Name Type Description Default
call str | Sequence[str]

The system call to make

required
cwd str | PathLike[str] | None

The working directory for the call

None
use_cache bool

Whether to cache the output of calls

False
Source code in src/jinjarope/envglobals.py
37
38
39
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
def get_output_from_call(
    call: str | Sequence[str],
    cwd: str | os.PathLike[str] | None = None,
    use_cache: bool = False,
) -> str | None:
    """Execute a system call and return its output as a string.

    Args:
        call: The system call to make
        cwd: The working directory for the call
        use_cache: Whether to cache the output of calls
    """
    import subprocess

    if not call:
        return None
    if not isinstance(call, str):
        call = " ".join(call)
    key = pathlib.Path(cwd or ".").resolve().as_posix() + call
    if key in _cache and use_cache:
        return _cache[key]
    logger.info("Executing %r...", call)
    try:
        text = subprocess.getoutput(call)
        _cache[key] = text
        return text  # noqa: TRY300
    except subprocess.CalledProcessError:
        logger.warning("Executing %s failed", call)
        return None

default

default(value: ~V, default_value: ~V = '', boolean: bool = False) -> ~V

If the value is undefined it will return the passed default value,

Aliases: d

Example

Jinja call:

{{ variable | default("some fallback") }}
Result: some fallback

DocStrings
Source code in .venv/lib/python3.12/site-packages/jinja2/filters.py
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
def do_default(
    value: V,
    default_value: V = "",  # type: ignore
    boolean: bool = False,
) -> V:
    """If the value is undefined it will return the passed default value,
    otherwise the value of the variable:

    .. sourcecode:: jinja

        {{ 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`:

    .. sourcecode:: jinja

        {{ ''|default('the string was empty', true) }}

    .. versionchanged:: 2.11
       It's now possible to configure the :class:`~jinja2.Environment` with
       :class:`~jinja2.ChainableUndefined` to make the `default` filter work
       on nested elements and attributes that may contain undefined values
       in the chain without getting an :exc:`~jinja2.UndefinedError`.
    """
    if isinstance(value, Undefined) or (boolean and not value):
        return default_value

    return value

get_hash

get_hash(obj: Any, hash_length: int | None = 7) -> str

Get a Md5 hash for given object.

Example

Jinja call:

{{ "abc" | get_hash }}
Result: 9001509

DocStrings

Parameters:

Name Type Description Default
obj Any

The object to get a hash for ()

required
hash_length int | None

Optional cut-off value to limit length

7
Source code in src/jinjarope/utils.py
131
132
133
134
135
136
137
138
139
140
141
def get_hash(obj: Any, hash_length: int | None = 7) -> str:
    """Get a Md5 hash for given object.

    Args:
        obj: The object to get a hash for ()
        hash_length: Optional cut-off value to limit length
    """
    import hashlib

    hash_md5 = hashlib.md5(str(obj).encode("utf-8"))
    return hash_md5.hexdigest()[:hash_length]

getenv

getenv(key, default=None)

Get an environment variable, return None if it doesn't exist.

Example

Jinja call:

{{ "CI" | getenv }}
Result: true

DocStrings
Source code in python3.12/os.py
808
809
810
811
812
def getenv(key, default=None):
    """Get an environment variable, return None if it doesn't exist.
    The optional second argument can specify an alternate default.
    key, default and the result are str."""
    return environ.get(key, default)

hasattr

hasattr(obj, name, /)

Return whether the object has an attribute with the given name.

Example

Jinja call:

{{ "3" | hasattr("removeprefix") }}
Result: True

DocStrings

import_module

import_module(name, package=None)

Import a module.

Example

Jinja call:

{{ "jinja2" | import_module }}
Result: <module 'jinja2' from '/home/runner/work/jinjarope/jinjarope/.venv/lib/python3.12/site-packages/jinja2/__init__.py'>

DocStrings
Source code in importlib/__init__.py
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
def import_module(name, package=None):
    """Import a module.

    The 'package' argument is required when performing a relative import. It
    specifies the package to use as the anchor point from which to resolve the
    relative import to an absolute import.

    """
    level = 0
    if name.startswith('.'):
        if not package:
            raise TypeError("the 'package' argument is required to perform a "
                            f"relative import for {name!r}")
        for character in name:
            if character != '.':
                break
            level += 1
    return _bootstrap._gcd_import(name[level:], package, level)

load_file

load_file(path: 'str | os.PathLike[str]') -> 'str'

Return the text-content of file at given path.

Example

Jinja call:

{{ "github://phil65:mknodes@main/docs/icons.jinja" | load_file }}
Result: `## Emoji extension index

MkNodes provides a custom emoji index for the pymdownx.emoji extension in order to provide access to all > 180.000 icons provided by the Iconify framework.

:[ICONSET NAME]-[ICON NAME]:
Example:

:mdi-file:
becomes:

Info

For compatibility, icons can also be accessed from the same name as the Material-MkDocs icon index, making the MkNodes index a superset of the MkDocs-Material index.

:material-file: is an alias for :mdi-file:

Icon node

MkNodes also includes a node for Pyconify-Icons named [MkIcon][mknodes.MkIcon]. It can be used to include icons with custom color, rotation and size. `

DocStrings

Parameters:

Name Type Description Default
path str | PathLike[str]

The path to get str content from

required
Source code in src/jinjarope/envglobals.py
21
22
23
24
25
26
27
28
29
30
31
@dec.cache_with_transforms(arg_transformers={0: lambda p: upath.UPath(p).resolve()})
def load_file_cached(path: str | os.PathLike[str]) -> str:
    """Return the text-content of file at given path.

    Call is cached based on resolved file path.
    Also supports fsspec-style URLs and UPaths.

    Args:
        path: The path to get str content from
    """
    return upath.UPath(path).read_text("utf-8")

map

map(context: 'Context', value: Iterable[Any], *args: Any, **kwargs: Any) -> Iterable[Any]

Applies a filter on a sequence of objects or looks up an attribute.

Example

Jinja call:

{{ [1, cycler] | map(attribute="__doc__") }}
Result: <generator object sync_do_map at 0x7f34fe3b6140>

Example

Jinja call:

{{ ["HELLO", "WoRlD"] | map("lower") | list }}
Result: ['hello', 'world']

DocStrings
Source code in .venv/lib/python3.12/site-packages/jinja2/filters.py
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
@async_variant(sync_do_map)  # type: ignore
async def do_map(
    context: "Context",
    value: t.Union[t.AsyncIterable[t.Any], t.Iterable[t.Any]],
    *args: t.Any,
    **kwargs: t.Any,
) -> t.AsyncIterable[t.Any]:
    if value:
        func = prepare_map(context, args, kwargs)

        async for item in auto_aiter(value):
            yield await auto_await(func(item))

match

match(obj: Any, mapping: dict[str | type, str] | None = None, **kwargs: Any) -> str

A filter trying to imitate a python match-case statement.

Example

Jinja call:

{{ "a" | match(a="Hit", b="miss") }}
Result: Hit

Example

Jinja call:

{{ 5 | match({int: "hit", str: "miss"}) }}
Result: hit

DocStrings

Parameters:

Name Type Description Default
obj Any

match object

required
mapping dict[str | type, str] | None

a mapping for the different cases. If key is type, an isinstance will be performed. If key is a str, check for equality.

None
kwargs Any

Same functionality as mapping, but provided as keyword arguments for convenience.

{}

Examples:

{{ "a" | match(a="hit", b="miss")
{{ MyClass() | match({MyClass: "hit", OtherClass: "miss"}) }}
Source code in src/jinjarope/envglobals.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
def match(obj: Any, mapping: dict[str | type, str] | None = None, **kwargs: Any) -> str:
    """A filter trying to imitate a python match-case statement.

    Args:
        obj: match object
        mapping: a mapping for the different cases. If key is type, an isinstance will
                 be performed. If key is a str, check for equality.
        kwargs: Same functionality as mapping, but provided as keyword arguments for
                convenience.

    Examples:
        ``` jinja
        {{ "a" | match(a="hit", b="miss")
        {{ MyClass() | match({MyClass: "hit", OtherClass: "miss"}) }}
        ```
    """
    # kwargs can only contain strs as keys, so we can perform simply getitem.
    if kwargs and obj in kwargs:
        return kwargs[obj]

    for k, v in (mapping or {}).items():
        match k:
            case type() if isinstance(obj, k):
                return v
            case _ if k == obj:
                return v
    return ""

partial

partial(fn: 'Callable', *args: 'Any', **kwargs: 'Any')

Create new function with partial application of given arguments / keywords.

Example

Jinja call:

{{ filters.path_join | partial("abc") }}
Result: functools.partial(<function join at 0x7f3519d1cb80>, 'abc')

DocStrings

Parameters:

Name Type Description Default
fn Callable

The function to generate a partial from

required
args Any

patially applied arguments

()
kwargs Any

partially applied keywords

{}
Source code in src/jinjarope/utils.py
29
30
31
32
33
34
35
36
37
def partial(fn: Callable, *args: Any, **kwargs: Any):
    """Create new function with partial application of given arguments / keywords.

    Args:
        fn: The function to generate a partial from
        args: patially applied arguments
        kwargs: partially applied keywords
    """
    return functools.partial(fn, *args, **kwargs)

random

random(context: 'Context', seq: 't.Sequence[V]') -> 't.Union[V, Undefined]'

Return a random item from the sequence.

Example

Jinja call:

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

DocStrings
Source code in .venv/lib/python3.12/site-packages/jinja2/filters.py
682
683
684
685
686
687
688
@pass_context
def do_random(context: "Context", seq: "t.Sequence[V]") -> "t.Union[V, Undefined]":
    """Return a random item from the sequence."""
    try:
        return random.choice(seq)
    except IndexError:
        return context.environment.undefined("No random item, sequence was empty.")

ternary

ternary(value: Any, true_val: Any, false_val: Any, none_val: Any = None)

Value ? true_val : false_val.

Example

Jinja call:

{{ True | ternary("A", "B") }}
Result: A

DocStrings

Parameters:

Name Type Description Default
value Any

The value to check.

required
true_val Any

The value to return if given value is true-ish

required
false_val Any

The value to return if given value is false-ish

required
none_val Any

Optional value to return if given value is None

None
Source code in src/jinjarope/envglobals.py
79
80
81
82
83
84
85
86
87
88
89
90
def ternary(value: Any, true_val: Any, false_val: Any, none_val: Any = None):
    """Value ? true_val : false_val.

    Args:
        value: The value to check.
        true_val: The value to return if given value is true-ish
        false_val: The value to return if given value is false-ish
        none_val: Optional value to return if given value is None
    """
    if value is None and none_val is not None:
        return none_val
    return true_val if bool(value) else false_val