Skip to content

html (16)

ansi2html

ansi2html(ansi_string: str, styles: dict[int, dict[str, str]] | None = None) -> str

Convert ansi string to colored HTML.

Example

Jinja call:

{{ "\033[31;1;4mHello\033[0m" | ansi2html }}
Result: <span style="color: red; font_weight: bold; text_decoration: underline">Hello</span>

DocStrings

Parameters:

Name Type Description Default
ansi_string str

text with ANSI color codes.

required
styles dict[int, dict[str, str]] | None

A mapping from ANSI codes to a dict with css

None

Returns:

Type Description
str

HTML string

Source code in src/jinjarope/htmlfilters.py
def ansi2html(ansi_string: str, styles: dict[int, dict[str, str]] | None = None) -> str:
    """Convert ansi string to colored HTML.

    Args:
        ansi_string: text with ANSI color codes.
        styles: A mapping from ANSI codes to a dict with css

    Returns:
        HTML string
    """
    styles = styles or ANSI_STYLES
    previous_end = 0
    in_span = False
    ansi_codes: list[int] = []
    ansi_finder = re.compile("\033\\[([\\d;]*)([a-zA-z])")
    parts = []
    for match in ansi_finder.finditer(ansi_string):
        parts.append(ansi_string[previous_end : match.start()])
        previous_end = match.end()
        params, command = match.groups()

        if command not in "mM":
            continue

        try:
            params = [int(p) for p in params.split(";")]
        except ValueError:
            params = [0]

        for i, v in enumerate(params):
            if v == 0:
                params = params[i + 1 :]
                if in_span:
                    in_span = False
                    parts.append("</span>")
                ansi_codes = []
                if not params:
                    continue

        ansi_codes.extend(params)
        if in_span:
            parts.append("</span>")
            in_span = False

        if not ansi_codes:
            continue

        style = [
            "; ".join([f"{k}: {v}" for k, v in styles[k].items()]).strip()
            for k in ansi_codes
            if k in styles
        ]
        parts.append(f'<span style="{"; ".join(style)}">')

        in_span = True

    parts.append(ansi_string[previous_end:])
    if in_span:
        parts.append("</span>")
        in_span = False
    return "".join(parts)

clean_svg

clean_svg(text: str) -> str

Strip off unwanted stuff from svg text which might be added by external libs.

Example

Jinja call:

{{ '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<body></body>' | clean_svg }}
Result: <body></body>

DocStrings

Parameters:

Name Type Description Default
text str

The text to cleanup / filter

required
Source code in src/jinjarope/htmlfilters.py
def clean_svg(text: str) -> str:
    """Strip off unwanted stuff from svg text which might be added by external libs.

    Removes xml headers and doctype declarations.

    Args:
        text: The text to cleanup / filter
    """
    text = re.sub(r"<\?xml version.*\?>\s*", "", text, flags=re.DOTALL)
    text = re.sub(r"<!DOCTYPE svg.*?>", "", text, flags=re.DOTALL)
    return text.strip()

format_css_rule

format_css_rule(dct: 'Mapping[str, Any]') -> 'str'

Format a nested dictionary as CSS rule.

Example

Jinja call:

{{ {"a": {"b": "c"} } | format_css_rule }}
Result: `a { b: c; }

`

DocStrings

Parameters:

Name Type Description Default
dct Mapping[str, Any]

The mapping to convert to CSS text

required
Source code in src/jinjarope/htmlfilters.py
def format_css_rule(dct: Mapping[str, Any]) -> str:
    """Format a nested dictionary as CSS rule.

    Mapping must be of shape {".a": {"b": "c"}}

    Args:
        dct: The mapping to convert to CSS text
    """
    data: dict[str, list[str]] = {}

    def _parse(obj: Mapping[str, Any], selector: str = "") -> None:
        for key, value in obj.items():
            if hasattr(value, "items"):
                rule = selector + " " + key
                data[rule] = []
                _parse(value, rule)

            else:
                prop = data[selector]
                prop.append(f"\t{key}: {value};\n")

    _parse(dct)
    string = ""
    for key, value in sorted(data.items()):
        if data[key]:
            string += key[1:] + " {\n" + "".join(value) + "}\n\n"
    return string

format_js_map

format_js_map(mapping: dict[str, typing.Any] | str, indent: int = 4) -> str

Return JS map str for given dictionary.

Example

Jinja call:

{{ {"abc": "def"} | format_js_map }}
Result: { abc: 'def', }

DocStrings

Parameters:

Name Type Description Default
mapping dict[str, Any] | str

Dictionary to dump

required
indent int

The amount of indentation for the key-value pairs

4
Source code in src/jinjarope/htmlfilters.py
def format_js_map(mapping: dict[str, Any] | str, indent: int = 4) -> str:
    """Return JS map str for given dictionary.

    Args:
        mapping: Dictionary to dump
        indent: The amount of indentation for the key-value pairs
    """
    import anyenv

    dct = anyenv.load_json(mapping) if isinstance(mapping, str) else mapping
    rows: list[str] = []
    indent_str = " " * indent
    for k, v in dct.items():
        match v:
            case bool():
                rows.append(f"{indent_str}{k}: {str(v).lower()},")
            case dict():
                rows.append(f"{indent_str}{k}: {format_js_map(v)},")
            case None:
                rows.append(f"{indent_str}{k}: null,")
            case _:
                rows.append(f"{indent_str}{k}: {v!r},")
    row_str = "\n" + "\n".join(rows) + "\n"
    return f"{{{row_str}}}"

format_xml

format_xml(str_or_elem: 'str | ET.Element', indent: 'str | int' = ' ', level: 'int' = 0, method: "Literal['xml', 'html', 'text', 'c14n']" = 'html', short_empty_elements: 'bool' = True, add_declaration: 'bool' = False) -> 'str'

(Pretty)print given XML.

Example

Jinja call:

{{ '<a><b><c>Hello!</c></b></a>' | format_xml }}
Result: <a> <b> <c>Hello!</c> </b> </a>

Example

Jinja call:

{{ '<a><b><c>Hello!</c></b></a>' | format_xml(indent=4) }}
Result: <a> <b> <c>Hello!</c> </b> </a>

Example

Jinja call:

{{ '<br></br>' | format_xml(short_empty_elements=True, method="xml") }}
Result: <br />

Example

Jinja call:

{{ '<br></br>' | format_xml(short_empty_elements=True, add_declaration=True, method="xml") }}
Result: <?xml version='1.0' encoding='utf-8'?> <br />

DocStrings

Parameters:

Name Type Description Default
str_or_elem str | Element

XML to prettyprint

required
indent str | int

Amount of spaces to use for indentation

' '
level int

Initial indentation level

0
method Literal['xml', 'html', 'text', 'c14n']

Output method

'html'
short_empty_elements bool

Whether empty elements should get printed in short form (applies when mode is "xml")

True
add_declaration bool

whether a XML declaration should be printed (applies when mode is "xml")

False
Source code in src/jinjarope/htmlfilters.py
@functools.lru_cache
def format_xml(
    str_or_elem: str | ET.Element,
    indent: str | int = "  ",
    level: int = 0,
    method: Literal["xml", "html", "text", "c14n"] = "html",
    short_empty_elements: bool = True,
    add_declaration: bool = False,
) -> str:
    """(Pretty)print given XML.

    Args:
        str_or_elem: XML to prettyprint
        indent: Amount of spaces to use for indentation
        level: Initial indentation level
        method: Output method
        short_empty_elements: Whether empty elements should get printed in short form
                              (applies when mode is "xml")
        add_declaration: whether a XML declaration should be printed
                         (applies when mode is "xml")
    """
    from xml.etree import ElementTree as ET

    if isinstance(str_or_elem, str):
        str_or_elem = ET.fromstring(str_or_elem)
    space = indent if isinstance(indent, str) else indent * " "
    ET.indent(str_or_elem, space=space, level=level)
    return ET.tostring(
        str_or_elem,
        encoding="unicode",
        method=method,
        xml_declaration=add_declaration,
        short_empty_elements=short_empty_elements,
    )

html_link(text: str | None = None, link: str | None = None, **kwargs: Any) -> str

Create a html link.

Example

Jinja call:

{{ "Test" | html_link("https://google.com") }}
Result: <a href='https://google.com'>Test</a>

DocStrings

Parameters:

Name Type Description Default
text str | None

Text to show for the link

None
link str | None

Target url

None
kwargs Any

additional key-value pairs to be inserted as attributes. Key strings will have "_" stripped from the end to allow using keywords.

{}
Source code in src/jinjarope/htmlfilters.py
def html_link(text: str | None = None, link: str | None = None, **kwargs: Any) -> str:
    """Create a html link.

    If link is empty string or None, just the text will get returned.

    Args:
        text: Text to show for the link
        link: Target url
        kwargs: additional key-value pairs to be inserted as attributes.
                Key strings will have "_" stripped from the end to allow using keywords.
    """
    if not link:
        return text or ""
    attrs = [f'{k.rstrip("_")}="{v}"' for k, v in kwargs.items()]
    attr_str = (" " + " ".join(attrs)) if attrs else ""
    return f"<a href={link!r}{attr_str}>{text or link}</a>"

inject_javascript

inject_javascript(html_content: ContentType, javascript: str, *, position: Literal['body', 'head', 'end_head', 'end_body'] = 'end_body') -> ContentType

Injects JavaScript code into an HTML string or bytes object.

Example

Jinja call:

{{ "<body>some HTML</body>" | inject_javascript("var number = 1;") }}
Result: <body>some HTML<script>var number = 1;</script></body>

Example

Jinja call:

{{ "<head>HEAD</head><body>some HTML</body>" | inject_javascript("var number = 1;", position="head") }}
Result: <head><script>var number = 1;</script>HEAD</head><body>some HTML</body>

DocStrings

Parameters:

Name Type Description Default
html_content ContentType

The HTML content to inject the JavaScript into

required
javascript str

The JavaScript code to inject

required
position Position

The position to inject the JavaScript ('body' by default)

'end_body'

Returns:

Type Description
ContentType

The modified HTML content with the same type as the input

Raises:

Type Description
ValueError

If the specified position tag is not found in the HTML content

TypeError

If the input type is neither str nor bytes

Source code in src/jinjarope/htmlfilters.py
def inject_javascript[ContentType: (str, bytes)](
    html_content: ContentType,
    javascript: str,
    *,
    position: Position = "end_body",
) -> ContentType:
    """Injects JavaScript code into an HTML string or bytes object.

    Args:
        html_content: The HTML content to inject the JavaScript into
        javascript: The JavaScript code to inject
        position: The position to inject the JavaScript ('body' by default)

    Returns:
        The modified HTML content with the same type as the input

    Raises:
        ValueError: If the specified position tag is not found in the HTML content
        TypeError: If the input type is neither str nor bytes
    """
    # Convert bytes to str if needed
    is_bytes = isinstance(html_content, bytes)
    working_content: str = html_content.decode() if is_bytes else html_content  # type: ignore[assignment, attr-defined]

    # Prepare the JavaScript tag
    script_tag = f"<script>{javascript}</script>"

    # Define the injection patterns
    patterns = {
        "body": (r"<body[^>]*>", lambda m: f"{m.group(0)}{script_tag}"),
        "head": (r"<head[^>]*>", lambda m: f"{m.group(0)}{script_tag}"),
        "end_head": (r"</head>", lambda m: f"{script_tag}{m.group(0)}"),
        "end_body": (r"</body>", lambda m: f"{script_tag}{m.group(0)}"),
    }

    if position not in patterns:
        msg = f"Invalid position: {position}. Must be one of {list(patterns.keys())}"
        raise ValueError(msg)

    pattern, replacement = patterns[position]
    modified_content = re.sub(pattern, replacement, working_content, count=1)

    # If no substitution was made, the tag wasn't found
    if modified_content == working_content:
        msg = f"Could not find {position} tag in HTML content"
        raise ValueError(msg)
    # Return the same type as input
    return modified_content.encode() if is_bytes else modified_content  # ty: ignore[invalid-explicit-return]

normalize_url

normalize_url(path: str, url: str | None = None, base: str = '') -> str

Return a URL relative to the given url or using the base.

Example

Jinja call:

{{ "test" | normalize_url(base="https://phil65.github.io") }}
Result: https://phil65.github.io/test

DocStrings

Parameters:

Name Type Description Default
path str

The path to normalize

required
url str | None

Optional relative url

None
base str

Base path

''
Source code in src/jinjarope/htmlfilters.py
def normalize_url(path: str, url: str | None = None, base: str = "") -> str:
    """Return a URL relative to the given url or using the base.

    Args:
        path: The path to normalize
        url: Optional relative url
        base: Base path
    """
    path, relative_level = _get_norm_url(path)
    if relative_level == -1:
        return path
    if url is None:
        return posixpath.join(base, path)
    result = relative_url(url, path)
    if relative_level > 0:
        result = "../" * relative_level + result
    return result

relative_url

relative_url(url_a: str, url_b: str) -> str

Compute the relative path from URL A to URL B.

Example

Jinja call:

{{ "https://phil65.github.io" | relative_url("https://phil65.github.io/mknodes") }}
Result: mknodes

DocStrings

Parameters:

Name Type Description Default
url_a str

URL A.

required
url_b str

URL B.

required

Returns:

Type Description
str

The relative URL to go from A to B.

Source code in src/jinjarope/htmlfilters.py
def relative_url(url_a: str, url_b: str) -> str:
    """Compute the relative path from URL A to URL B.

    Args:
        url_a: URL A.
        url_b: URL B.

    Returns:
        The relative URL to go from A to B.
    """
    parts_a = url_a.split("/")
    if "#" in url_b:
        url_b, anchor = url_b.split("#", 1)
    else:
        anchor = None
    parts_b = url_b.split("/")

    # remove common left parts
    while parts_a and parts_b and parts_a[0] == parts_b[0]:
        parts_a.pop(0)
        parts_b.pop(0)

    # go up as many times as remaining a parts' depth
    levels = len(parts_a) - 1
    parts_relative = [".."] * levels + parts_b
    relative = "/".join(parts_relative)
    return f"{relative}#{anchor}" if anchor else relative

relative_url_mkdocs

relative_url_mkdocs(url: str, other: str) -> str

Return given url relative to other (MkDocs implementation).

Example

Jinja call:

{{ "https://phil65.github.io" | relative_url_mkdocs("https://phil65.github.io/mknodes") }}
Result: ..

DocStrings

Parameters:

Name Type Description Default
url str

URL A.

required
other str

URL B.

required
Source code in src/jinjarope/htmlfilters.py
def relative_url_mkdocs(url: str, other: str) -> str:
    """Return given url relative to other (MkDocs implementation).

    Both are operated as slash-separated paths, similarly to the 'path' part of a URL.
    The last component of `other` is skipped if it contains a dot (considered a file).
    Actual URLs (with schemas etc.) aren't supported. The leading slash is ignored.
    Paths are normalized ('..' works as parent directory), but going higher than the
    root has no effect ('foo/../../bar' ends up just as 'bar').

    Args:
        url: URL A.
        other: URL B.
    """
    # Remove filename from other url if it has one.
    dirname, _, basename = other.rpartition("/")
    if "." in basename:
        other = dirname

    other_parts = _norm_parts(other)
    dest_parts = _norm_parts(url)
    common = 0
    for a, b in zip(other_parts, dest_parts):
        if a != b:
            break
        common += 1

    rel_parts = [".."] * (len(other_parts) - common) + dest_parts[common:]
    relurl = "/".join(rel_parts) or "."
    return relurl + "/" if url.endswith("/") else relurl

svg_to_data_uri

svg_to_data_uri(svg: str) -> str

Wrap svg as data URL.

Example

Jinja call:

{{ "<svg>...</svg>" | svg_to_data_uri }}
Result: url('data:image/svg+xml;charset=utf-8,<svg>...</svg>')

DocStrings

Parameters:

Name Type Description Default
svg str

The svg to wrap into a data URL

required
Source code in src/jinjarope/htmlfilters.py
def svg_to_data_uri(svg: str) -> str:
    """Wrap svg as data URL.

    Args:
        svg: The svg to wrap into a data URL
    """
    if not isinstance(svg, str):
        msg = "Invalid type: %r"
        raise TypeError(msg, type(svg))
    return f"url('data:image/svg+xml;charset=utf-8,{svg}')"

url_to_b64

url_to_b64(image_url: str) -> str | None

Convert an image URL to a base64-encoded string.

Required packages: httpx2

Example

Jinja call:

{{ "https://picsum.photos/100/100" | url_to_b64 }}
Result: /9j/4QDeRXhpZgAASUkqAAgAAAAGABIBAwABAAAAAQAAABoBBQABAAAAVgAAABsBBQABAAAAXgAAACgBAwABAAAAAgAAABMCAwABAAAAAQAAAGmHBAABAAAAZgAAAAAAAABIAAAAAQAAAEgAAAABAAAABwAAkAcABAAAADAyMTABkQcABAAAAAECAwCGkgcAFgAAAMAAAAAAoAcABAAAADAxMDABoAMAAQAAAP//AAACoAQAAQAAAGQAAAADoAQAAQAAAGQAAAAAAAAAQVNDSUkAAABQaWNzdW0gSUQ6IDYzNf/bAEMACAYGBwYFCAcHBwkJCAoMFA0MCwsMGRITDxQdGh8eHRocHCAkLicgIiwjHBwoNyksMDE0NDQfJzk9ODI8LjM0Mv/bAEMBCQkJDAsMGA0NGDIh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SzWUReoZsAXy5BwvDCeP3kzwKOTCXtydYHgRh8BNKo/jGAJ4Gr9Ybuj5H9sA6r2jx6YKfUtMTDI4gt2eMLG5mkcZCuQgEg6xQgvK1koIfNxhINa8YM+Jie8BwehpU8ZHun1kGFUBoCjlEe66x/TGrmK8NN1iNc7wIU/Fy02zfbFZI/GD0ygSmSCYtXFvRAAbcpmG+XYHKd5pXTtfczQxYvjBTziBCQE2vrKAjwav9MguXgTNl3oE2oOCV/pA+sHTF/kP0ZbVYQbORxlyg1D4B8YJ9pRAoe2k4xKU8rF6C/8AXHW1CBlPd04e0oIRKtPM9YjonxtMGIhmpKgcO/eOoCTQOnVwZMSwJtYBjQw4fxhI3tDAAK8OdccNBsdJWHrkuPUF6y8zouShxAzq2XnAaQAhb8L38YJMEmF96H95dUAw7kkdJ53jt49xEPDNP1gHS7k8gJqPAEyIgLHKT+MNHIheGK7niDD84pCXpzi0R0Kh0YT9RHnAOepBIAF4bb3goSOFOsR1NwqDIETfRjov8mD4IF+fxm8kCdQEfZbccFSEC34manOXsATeNL2BNP6yKpO9auV6+zChNTiOGNo47SM42hFm8B1dMSuT6BXsSL8ZO9uXs/8AGTkAyIuvGJMSPsxuBP0ODIvRETCukXiRx8uNwTURI037zcyOkOg/vNoMCvEeo7wuTHGz941SqeYuUIe8RmWwDh6yJBOQzGwEa53h6b9zeVtWCJDOIh9mQEWb3N5G0pPSlcDUGAgIsmEMlAwiPxlySQmyg4pN/wAk4xB2h8ZS1sQ3iDy95E/Y4Bcq8/8ADDqQnGLRvOf/2Q==

DocStrings

Parameters:

Name Type Description Default
image_url str

The URL of the image to convert.

required

Returns:

Type Description
str | None

The base64-encoded string of the image.

Raises:

Type Description
HTTPError

If there's an error downloading the image.

Source code in src/jinjarope/htmlfilters.py
def url_to_b64(image_url: str) -> str | None:
    """Convert an image URL to a base64-encoded string.

    Args:
        image_url: The URL of the image to convert.

    Returns:
        The base64-encoded string of the image.

    Raises:
        httpx2.HTTPError: If there's an error downloading the image.
    """
    import httpx2

    # Download the image
    with httpx2.Client(follow_redirects=True) as client:
        response = client.get(image_url)
        response.raise_for_status()
        image_data = response.content

    # Encode the image to base64
    return base64.b64encode(image_data).decode("utf-8")

urlencode

urlencode(value: Union[str, Mapping[str, Any], Iterable[Tuple[str, Any]]]) -> str

Quote data for use in a URL path or query using UTF-8.

Example

Jinja call:

{{ "Some text" | urlencode }}
Result: Some%20text

Example

Jinja call:

{{ {"key": "value with spaces"} | urlencode }}
Result: key=value+with+spaces

DocStrings
Source code in jinja2/filters.py
def do_urlencode(
    value: t.Union[str, t.Mapping[str, t.Any], t.Iterable[t.Tuple[str, t.Any]]],
) -> str:
    """Quote data for use in a URL path or query using UTF-8.

    Basic wrapper around :func:`urllib.parse.quote` when given a
    string, or :func:`urllib.parse.urlencode` for a dict or iterable.

    :param value: Data to quote. A string will be quoted directly. A
        dict or iterable of ``(key, value)`` pairs will be joined as a
        query string.

    When given a string, "/" is not quoted. HTTP servers treat "/" and
    "%2F" equivalently in paths. If you need quoted slashes, use the
    ``|replace("/", "%2F")`` filter.

    .. versionadded:: 2.7
    """
    if isinstance(value, str) or not isinstance(value, abc.Iterable):
        return url_quote(value)

    if isinstance(value, dict):
        items: t.Iterable[t.Tuple[str, t.Any]] = value.items()
    else:
        items = value  # type: ignore

    return "&".join(
        f"{url_quote(k, for_qs=True)}={url_quote(v, for_qs=True)}" for k, v in items
    )

urlize

urlize(eval_ctx: 'EvalContext', value: str, trim_url_limit: Optional[int] = None, nofollow: bool = False, target: Optional[str] = None, rel: Optional[str] = None, extra_schemes: Optional[Iterable[str]] = None) -> str

Convert URLs in text into clickable links.

Example

Jinja call:

{{ "some text" | urlize }}
Result: some text

Example

Jinja call:

{{ "https://example.com" | urlize(target="_blank") }}
Result: <a href="https://example.com" rel="noopener" target="_blank">https://example.com</a>

DocStrings
Source code in jinja2/filters.py
@pass_eval_context
def do_urlize(
    eval_ctx: "EvalContext",
    value: str,
    trim_url_limit: t.Optional[int] = None,
    nofollow: bool = False,
    target: t.Optional[str] = None,
    rel: t.Optional[str] = None,
    extra_schemes: t.Optional[t.Iterable[str]] = None,
) -> str:
    """Convert URLs in text into clickable links.

    This may not recognize links in some situations. Usually, a more
    comprehensive formatter, such as a Markdown library, is a better
    choice.

    Works on ``http://``, ``https://``, ``www.``, ``mailto:``, and email
    addresses. Links with trailing punctuation (periods, commas, closing
    parentheses) and leading punctuation (opening parentheses) are
    recognized excluding the punctuation. Email addresses that include
    header fields are not recognized (for example,
    ``mailto:address@example.com?cc=copy@example.com``).

    :param value: Original text containing URLs to link.
    :param trim_url_limit: Shorten displayed URL values to this length.
    :param nofollow: Add the ``rel=nofollow`` attribute to links.
    :param target: Add the ``target`` attribute to links.
    :param rel: Add the ``rel`` attribute to links.
    :param extra_schemes: Recognize URLs that start with these schemes
        in addition to the default behavior. Defaults to
        ``env.policies["urlize.extra_schemes"]``, which defaults to no
        extra schemes.

    .. versionchanged:: 3.0
        The ``extra_schemes`` parameter was added.

    .. versionchanged:: 3.0
        Generate ``https://`` links for URLs without a scheme.

    .. versionchanged:: 3.0
        The parsing rules were updated. Recognize email addresses with
        or without the ``mailto:`` scheme. Validate IP addresses. Ignore
        parentheses and brackets in more cases.

    .. versionchanged:: 2.8
       The ``target`` parameter was added.
    """
    policies = eval_ctx.environment.policies
    rel_parts = set((rel or "").split())

    if nofollow:
        rel_parts.add("nofollow")

    rel_parts.update((policies["urlize.rel"] or "").split())
    rel = " ".join(sorted(rel_parts)) or None

    if target is None:
        target = policies["urlize.target"]

    if extra_schemes is None:
        extra_schemes = policies["urlize.extra_schemes"] or ()

    for scheme in extra_schemes:
        if _uri_scheme_re.fullmatch(scheme) is None:
            raise FilterArgumentError(f"{scheme!r} is not a valid URI scheme prefix.")

    rv = urlize(
        value,
        trim_url_limit=trim_url_limit,
        rel=rel,
        target=target,
        extra_schemes=extra_schemes,
    )

    if eval_ctx.autoescape:
        rv = Markup(rv)

    return rv

wrap_in_elem

wrap_in_elem(text: str | None, tag: str, add_linebreaks: bool = False, **kwargs: Any) -> str

Wrap given text in an HTML/XML tag (with attributes).

Example

Jinja call:

{{ "abc" | wrap_in_elem("test") }}
Result: <test>abc</test>

DocStrings

Parameters:

Name Type Description Default
text str | None

Text to wrap

required
tag str

Tag to wrap text in

required
add_linebreaks bool

Adds a linebreak before and after the text

False
kwargs Any

additional key-value pairs to be inserted as attributes for tag. Key strings will have "_" stripped from the end to allow using keywords.

{}
Source code in src/jinjarope/htmlfilters.py
def wrap_in_elem(text: str | None, tag: str, add_linebreaks: bool = False, **kwargs: Any) -> str:
    """Wrap given text in an HTML/XML tag (with attributes).

    If text is empty, just return an empty string.

    Args:
        text: Text to wrap
        tag: Tag to wrap text in
        add_linebreaks: Adds a linebreak before and after the text
        kwargs: additional key-value pairs to be inserted as attributes for tag.
                Key strings will have "_" stripped from the end to allow using keywords.
    """
    if not text:
        return ""
    attrs = [f'{k.rstrip("_")}="{v}"' for k, v in kwargs.items()]
    attr_str = (" " + " ".join(attrs)) if attrs else ""
    nl = "\n" if add_linebreaks else ""
    return f"<{tag}{attr_str}>{nl}{text}{nl}</{tag}>"

xmlattr

xmlattr(eval_ctx: 'EvalContext', d: Mapping[str, Any], autospace: bool = True) -> str

Create an SGML/XML attribute string based on the items in a dict.

Example

Jinja call:

<ul{{ {'class': 'my_list', 'missing': none,
        'id': 'some-id'}|xmlattr }}>
Result: <ul class="my_list" id="some-id">

Example

Jinja call:

<div{{ {'data-items': ['a', 'b'], 'disabled': true}|xmlattr }}>
Result: <div data-items="[&#39;a&#39;, &#39;b&#39;]" disabled="True">

DocStrings
Source code in jinja2/filters.py
@pass_eval_context
def do_xmlattr(
    eval_ctx: "EvalContext", d: t.Mapping[str, t.Any], autospace: bool = True
) -> str:
    """Create an SGML/XML attribute string based on the items in a dict.

    **Values** that are neither ``none`` nor ``undefined`` are automatically
    escaped, safely allowing untrusted user input.

    User input should not be used as **keys** to this filter. If any key
    contains a space, ``/`` solidus, ``>`` greater-than sign, or ``=`` equals
    sign, this fails with a ``ValueError``. Regardless of this, user input
    should never be used as keys to this filter, or must be separately validated
    first.

    .. sourcecode:: html+jinja

        <ul{{ {'class': 'my_list', 'missing': none,
                'id': 'list-%d'|format(variable)}|xmlattr }}>
        ...
        </ul>

    Results in something like this:

    .. sourcecode:: html

        <ul class="my_list" id="list-42">
        ...
        </ul>

    As you can see it automatically prepends a space in front of the item
    if the filter returned something unless the second parameter is false.

    .. versionchanged:: 3.1.4
        Keys with ``/`` solidus, ``>`` greater-than sign, or ``=`` equals sign
        are not allowed.

    .. versionchanged:: 3.1.3
        Keys with spaces are not allowed.
    """
    items = []

    for key, value in d.items():
        if value is None or isinstance(value, Undefined):
            continue

        if _attr_key_re.search(key) is not None:
            raise ValueError(f"Invalid character in attribute name: {key!r}")

        items.append(f'{escape(key)}="{escape(value)}"')

    rv = " ".join(items)

    if autospace and rv:
        rv = " " + rv

    if eval_ctx.autoescape:
        rv = Markup(rv)

    return rv