Skip to content

format (11)

dirname_to_title

dirname_to_title(dirname: 'str | os.PathLike[str]') -> 'str'

Return a page tile obtained from a directory name.

Example

Jinja call:

{{ "a_foldername" | dirname_to_title }}
Result: A foldername

DocStrings

Parameters:

Name Type Description Default
dirname str | PathLike[str]

directory to get a title for

required
Source code in src/jinjarope/textfilters.py
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
def dirname_to_title(dirname: str | os.PathLike[str]) -> str:
    """Return a page tile obtained from a directory name.

    Replaces dashes and underscores with spaces and capitalizes the first letter
    in case all letters are lowercase

    Args:
        dirname: directory to get a title for
    """
    title = str(dirname)
    title = title.replace("-", " ").replace("_", " ")
    if title.lower() == title:
        title = title.capitalize()

    return title

extract_body

extract_body(src: str) -> str

Get body of source code of given function / class.

Example

Jinja call:

{{
"@deprecated
def test(a):
    b = a
" | extract_body }}
Result: b = a

DocStrings

Parameters:

Name Type Description Default
src str

Source code to extract the body from

required
Source code in src/jinjarope/textfilters.py
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
@functools.cache
def extract_body(src: str) -> str:
    """Get body of source code of given function / class.

    Strips off the signature / decorators.

    Args:
        src: Source code to extract the body from
    """
    # see https://stackoverflow.com/questions/38050649
    lines = src.split("\n")
    src_lines = itertools.dropwhile(lambda x: x.strip().startswith("@"), lines)
    line = next(src_lines).strip()  # type: ignore
    if not line.startswith(("def ", "class ")):
        return line.rsplit(":")[-1].strip()
    if not line.endswith(":"):
        for line in src_lines:
            line = line.strip()
            if line.endswith(":"):
                break
    return "".join(src_lines)

format

format(value: str, *args: Any, **kwargs: Any) -> str

Apply the given values to a printf-style_ format string, like

Example

Jinja call:

{{ "{test}" | format(test="abc") }}
Result: {test}

Example

Jinja call:

{{ "%s, %s!" | format("Hello", "World") }}
Result: Hello, World!

DocStrings
Source code in .venv/lib/python3.12/site-packages/jinja2/filters.py
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
def do_format(value: str, *args: t.Any, **kwargs: t.Any) -> str:
    """Apply the given values to a `printf-style`_ format string, like
    ``string % values``.

    .. sourcecode:: jinja

        {{ "%s, %s!"|format(greeting, name) }}
        Hello, World!

    In most cases it should be more convenient and efficient to use the
    ``%`` operator or :meth:`str.format`.

    .. code-block:: text

        {{ "%s, %s!" % (greeting, name) }}
        {{ "{}, {}!".format(greeting, name) }}

    .. _printf-style: https://docs.python.org/library/stdtypes.html
        #printf-style-string-formatting
    """
    if args and kwargs:
        raise FilterArgumentError(
            "can't handle positional and keyword arguments at the same time"
        )

    return soft_str(value) % (kwargs or args)

format_code

format_code(code: str, line_length: int = 100)

Format code to given line length using black.

Example

Jinja call:

{{ "AVeryLargeCodeBlock(a_parameter=3, another_parameter=4, abc=False)" | format_code }}
Result: AVeryLargeCodeBlock(a_parameter=3, another_parameter=4, abc=False)

DocStrings

Parameters:

Name Type Description Default
code str

The code to format

required
line_length int

Line length limit for formatted code

100
Source code in src/jinjarope/textfilters.py
86
87
88
89
90
91
92
93
94
95
96
97
98
@functools.cache
def format_code(code: str, line_length: int = 100):
    """Format code to given line length using `black`.

    Args:
        code: The code to format
        line_length: Line length limit for formatted code
    """
    code = code.strip()
    if len(code) < line_length:
        return code
    formatter = utils._get_black_formatter()
    return formatter(code, line_length)

format_filter_signature

format_filter_signature(fn: 'Callable', filter_name: 'str', follow_wrapped: 'bool' = True, eval_str: 'bool' = False) -> 'str'

Create a signature for a jinja filter based on filter name and callable.

Example

Jinja call:

{{ filters.format_filter_signature | format_filter_signature("ffs") }}
Result: fn: 'Callable' | ffs(filter_name: 'str', follow_wrapped: 'bool' = True, eval_str: 'bool' = False) -> 'str'

DocStrings

Parameters:

Name Type Description Default
fn Callable

The callable to format the signature from

required
filter_name str

Name of the jinja filter

required
follow_wrapped bool

Whether to unwrap the callable

True
eval_str bool

Un-stringize annotations using eval

False
Source code in src/jinjarope/textfilters.py
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
def format_filter_signature(
    fn: Callable,
    filter_name: str,
    follow_wrapped: bool = True,
    eval_str: bool = False,
) -> str:
    """Create a signature for a jinja filter based on filter name and callable.

    Outputs text in shape of
    "code: 'str' | test(line_length: 'int' = 100)"

    Args:
        fn: The callable to format the signature from
        filter_name: Name of the jinja filter
        follow_wrapped: Whether to unwrap the callable
        eval_str: Un-stringize annotations using eval
    """
    sig = inspect.signature(fn, follow_wrapped=follow_wrapped, eval_str=eval_str)
    params = dict(sig._parameters)  # type: ignore[attr-defined]
    if hasattr(fn, "jinja_pass_arg"):
        # for @pass_xyz decorated functions
        params.pop(next(iter(params)))
    first_val = params.pop(next(iter(params)))
    sig._parameters = params  # type: ignore[attr-defined]
    return f"{first_val} | {filter_name}{sig}"

format_signature

format_signature(fn: 'Callable', follow_wrapped: 'bool' = True, eval_str: 'bool' = True, remove_jinja_arg: 'bool' = False) -> 'str'

Format signature of a callable.

Example

Jinja call:

{{ "".removesuffix | format_signature }}
Result: (suffix, /)

DocStrings

Parameters:

Name Type Description Default
fn Callable

The callable to format the signature from

required
follow_wrapped bool

Whether to unwrap the callable

True
eval_str bool

Un-stringize annotations using eval

True
remove_jinja_arg bool

If true, remove the first argument for pass_xyz decorated fns.

False
Source code in src/jinjarope/textfilters.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
@functools.cache
def format_signature(
    fn: Callable,
    follow_wrapped: bool = True,
    eval_str: bool = True,
    remove_jinja_arg: bool = False,
) -> str:
    """Format signature of a callable.

    Args:
        fn: The callable to format the signature from
        follow_wrapped: Whether to unwrap the callable
        eval_str: Un-stringize annotations using eval
        remove_jinja_arg: If true, remove the first argument for pass_xyz decorated fns.
    """
    if eval_str:
        try:
            sig = inspect.signature(fn, follow_wrapped=follow_wrapped, eval_str=True)
        except (TypeError, NameError):
            sig = inspect.signature(fn, follow_wrapped=follow_wrapped, eval_str=False)
    else:
        sig = inspect.signature(fn, follow_wrapped=follow_wrapped, eval_str=False)
    if remove_jinja_arg and hasattr(fn, "jinja_pass_arg"):
        # for @pass_xyz decorated functions
        params = dict(sig._parameters)  # type: ignore[attr-defined]
        params.pop(next(iter(params)))
        sig._parameters = params  # type: ignore[attr-defined]
    return str(sig)

pformat

pformat(object, indent=1, width=80, depth=None, *, compact=False, sort_dicts=True, underscore_numbers=False)

Format a Python object into a pretty-printed representation.

Example

Jinja call:

{{ ([1, 2, 3] * 10) | pformat }}
Result: [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]

DocStrings
Source code in python3.12/pprint.py
57
58
59
60
61
62
def pformat(object, indent=1, width=80, depth=None, *,
            compact=False, sort_dicts=True, underscore_numbers=False):
    """Format a Python object into a pretty-printed representation."""
    return PrettyPrinter(indent=indent, width=width, depth=depth,
                         compact=compact, sort_dicts=sort_dicts,
                         underscore_numbers=underscore_numbers).pformat(object)

pprint

pprint(value: Any) -> str

Pretty print a variable. Useful for debugging.

Example

Jinja call:

{{ ([10000] * 10) | pprint }}
Result: [10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000]

DocStrings
Source code in .venv/lib/python3.12/site-packages/jinja2/filters.py
724
725
726
def do_pprint(value: t.Any) -> str:
    """Pretty print a variable. Useful for debugging."""
    return pformat(value)

repr

repr(obj, /)

Return the canonical string representation of the object.

Example

Jinja call:

{{ "A" | repr }}
Result: 'A'

DocStrings

slugify

slugify(text: 'str | os.PathLike[str]') -> 'str'

Create a slug for given text.

Example

Jinja call:

{{ "Ä test" | slugify }}
Result: __test

DocStrings

Parameters:

Name Type Description Default
text str | PathLike[str]

text to get a slug for

required
Source code in src/jinjarope/textfilters.py
181
182
183
184
185
186
187
188
189
190
191
192
193
def slugify(text: str | os.PathLike[str]) -> str:
    """Create a slug for given text.

    Returned text only contains alphanumerical and underscore.

    Args:
        text: text to get a slug for
    """
    import re

    text = str(text).lower()
    text = re.sub("[^0-9a-zA-Z_.]", "_", text)
    return re.sub("^[^0-9a-zA-Z_#]+", "", text)

split_url

split_url(value: str, query: Optional[Literal['fragment', 'hostname', 'netloc', 'password', 'path', 'port', 'query', 'scheme', 'username']] = None) -> str | dict[str, str]

Split a URL into its parts (and optionally return a specific part).

Example

Jinja call:

{{ "scheme://netloc/path;parameters?query#fragment" | split_url }}
{{ "scheme://netloc/path;parameters?query#fragment" | split_url("path") }}
Result: {'fragment': 'fragment', 'hostname': 'netloc', 'netloc': 'netloc', 'password': None, 'path': '/path;parameters', 'port': None, 'query': 'query', 'scheme': 'scheme', 'username': None} /path;parameters

DocStrings

Parameters:

Name Type Description Default
value str

The URL to split

required
query QueryStr | None

Optional URL part to extract

None
Source code in src/jinjarope/htmlfilters.py
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
@functools.lru_cache
def split_url(value: str, query: QueryStr | None = None) -> str | dict[str, str]:
    """Split a URL into its parts (and optionally return a specific part).

    Args:
        value: The URL to split
        query: Optional URL part to extract
    """
    from urllib.parse import urlsplit

    def object_to_dict(obj: Any, exclude: list[str] | None = None) -> dict[str, Any]:
        """Converts an object into a dict making the properties into keys.

        Allows excluding certain keys.
        """
        if exclude is None or not isinstance(exclude, list):
            exclude = []
        return {
            key: getattr(obj, key)
            for key in dir(obj)
            if not (key.startswith("_") or key in exclude)
        }

    to_exclude = ["count", "index", "geturl", "encode"]
    results = object_to_dict(urlsplit(value), exclude=to_exclude)

    # If a query is supplied, make sure it's valid then return the results.
    # If no option is supplied, return the entire dictionary.
    if not query:
        return results
    if query not in results:
        msg = "split_url: unknown URL component: %s"
        raise ValueError(msg, query)
    return results[query]