Looping

It’s common in templating to format a list of items, for example, a <ul> list. Many Python template languages invent a Python-like grammar to do for loops and the like.

Simple Looping

You know what’s more Python-like? Python. f-strings can do looping in a Python expression using list comprehensions and so can viewdom:

def main() -> str:
    """Main entry point."""
    message = "Hello"
    names = ["World", "Universe"]
    result = render(
        html(
            """
      <ul title="{message}">
        {[
            html('<li>{name}</li>')
            for name in names
         ] }
      </li>
    """
        )
    )

    return result

Rendered Looping

You could also move the generation of the items out of the “parent” template, then use that VDOM result in the next template:

def main() -> str:
    """Main entry point."""
    message = "Hello"
    names = ["World", "Universe"]
    items = [html("<li>{label}</li>") for label in names]
    result = render(
        html(
            """
      <ul title="{message}">
        {items}
      </li>
    """
        )
    )
    return result