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
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
@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()
    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 jinja2/filters.py
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) -> str

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
@functools.cache
def format_code(code: str, line_length: int = 100) -> str:
    """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[..., Any]', 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[..., Any]' | ffs(filter_name: 'str', follow_wrapped: 'bool' = True, eval_str: 'bool' = False) -> 'str'

DocStrings

Parameters:

Name Type Description Default
fn Callable[..., Any]

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
def format_filter_signature(
    fn: Callable[..., Any],
    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[..., Any]', 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[..., Any]

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
@functools.cache
def format_signature(
    fn: Callable[..., Any],
    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.13/pprint.py
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 jinja2/filters.py
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
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
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]  # type: ignore[no-any-return]