Skip to content

add VDOM to HTML util function #435

Closed
@rmorshea

Description

@rmorshea

Sample implementation:

from html import escape as html_escape

def vdom_to_html(vdom: Union[str, VdomDict]) -> str:
    """Convert a VDOM dictionary into an HTML string

    Only the following keys are translated to HTML:

    - ``tagName``
    - ``attributes``
    - ``children`` (must be strings or more VDOM dicts)
    """
    if isinstance(vdom, str):
        return vdom

    try:
        tag = vdom["tagName"]
    except TypeError as error:
        raise TypeError(f"Expected a VDOM dictionary or string, not {vdom}") from error

    if "attributes" in vdom:
        attributes = " " + " ".join(
            f'{k}="{html_escape(v)}"' for k, v in vdom["attributes"].items()
        )
    else:
        attributes = ""

    if "children" in vdom:
        children = "".join(map(vdom_to_html, vdom["children"]))
    else:
        children = ""

    return f"<{tag}{attributes}>{children}</{tag}>"

Metadata

Metadata

Assignees

No one assigned

    Labels

    flag-good-first-issueA well defined and self-contained task.priority-3-lowMay be resolved one any timeline.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions