Skip to content

SVG

Render SVG markup with optional sanitization.


Quick Start

Live Preview
from faststrap import Svg

Svg(
    "<svg viewBox='0 0 120 32' width='120' height='32'>...</svg>",
)

Sanitization

Sanitization is enabled by default and uses bleach. Install the optional extras:

pip install "faststrap[markdown]"

To allow raw SVG as-is, disable sanitization:

Svg(svg_text, sanitize=False)

You can also pre-sanitize SVG strings with render_svg if you want to reuse output.


Theming

Use currentColor inside your SVG to inherit text color and automatically adapt to light and dark themes.


Parameters

Parameter Type Default Description
svg str required SVG markup.
sanitize bool True Sanitize SVG with bleach.
allowed_tags list[str] \| None None Override allowed SVG tags.
allowed_attributes dict[str, list[str]] \| None None Override allowed SVG attributes.
allowed_protocols list[str] \| None None Override allowed URL protocols.
**kwargs Any Extra wrapper attributes.

Security Notes

Only disable sanitization for trusted SVG markup. Treat user-provided SVG as untrusted input.


API Reference

faststrap.components.display.svg.render_svg(svg, *, sanitize=True, allowed_tags=None, allowed_attributes=None, allowed_protocols=None)

Render SVG markup with optional sanitization.

Source code in src/faststrap/components/display/svg.py
def render_svg(
    svg: str,
    *,
    sanitize: bool = True,
    allowed_tags: list[str] | None = None,
    allowed_attributes: dict[str, list[str]] | None = None,
    allowed_protocols: list[str] | None = None,
) -> str:
    """Render SVG markup with optional sanitization."""
    if not sanitize:
        return svg

    bleach_module = _load_bleach_module()
    return cast(
        str,
        bleach_module.clean(
            svg,
            tags=allowed_tags or DEFAULT_SVG_TAGS,
            attributes=allowed_attributes or DEFAULT_SVG_ATTRIBUTES,
            protocols=allowed_protocols or DEFAULT_SVG_PROTOCOLS,
            strip=True,
        ),
    )

faststrap.components.display.svg.Svg(svg, *, sanitize=True, allowed_tags=None, allowed_attributes=None, allowed_protocols=None, **kwargs)

Render raw SVG into a styled container.

Source code in src/faststrap/components/display/svg.py
@register(category="display")
@beta
def Svg(
    svg: str,
    *,
    sanitize: bool = True,
    allowed_tags: list[str] | None = None,
    allowed_attributes: dict[str, list[str]] | None = None,
    allowed_protocols: list[str] | None = None,
    **kwargs: Any,
) -> Div:
    """Render raw SVG into a styled container."""
    content = render_svg(
        svg,
        sanitize=sanitize,
        allowed_tags=allowed_tags,
        allowed_attributes=allowed_attributes,
        allowed_protocols=allowed_protocols,
    )

    user_cls = kwargs.pop("cls", "")
    attrs: dict[str, Any] = {
        "cls": merge_classes("faststrap-svg", user_cls),
    }
    attrs.update(convert_attrs(kwargs))
    return Div(NotStr(content), **attrs)