Components#

You often have a snippet of templating that you’d like to re-use. Many existing templating systems have “macros” for this: units of templating that can be re-used and called from other templates.

The whole mechanism, though, is quite magical:

  • Where do the macros come from? Multiple layers of context magic and specially-named directories provide the answer.

  • What macros are avaiable at the cursor position I’m at in a template? It’s hard for an editor or IDE to predict and provide autocomplete.

  • What are the macros arguments and what is this template’s special syntax for providing them? And can my editor help on autocomplete or telling me when I got it wrong (or the macro changed its signature)?

  • How does my current scope interact with the macro’s scope, and where does it get other parts of its scope from?

viewdom, courtesy of htm.py, makes this more Pythonic through the use of “components”. Instead of some sorta-callable, a component is a normal Python callable – e.g. a function – with normal Python arguments and return values.

Simple Heading#

Here is a component callable – a Heading function – which returns a VDOM:

def Heading():
    """The default heading."""
    return html("<h1>My Title</h1>")


def main() -> str:
    """Main entry point."""
    vdom = html("<{Heading} />")
    result = render(vdom)
    return result

Component in VDOM#

The VDOM now has something special in it: a callable as the “tag”, rather than a string such as <div>.

def Heading():
    """The default heading."""
    return html("<h1>My Title</h1>")


def main() -> VDOMNode:
    """Main entry point."""
    vdom = html("<{Heading} />")
    return vdom

What does that vdom node look like? This assertion shows that it is a VDOMNode:

    assert main() == VDOMNode(tag=Heading, props={}, children=[])

Simple Props#

As expected, components can have props, passed in as what looks like HTML attributes. Here we pass a title as an argument to Heading, using a simple HTML attribute string value:

def Heading(title):
    """Default heading."""
    return html("<h1>{title}</h1>")


def main() -> str:
    """Main entry point."""
    result = render(html('<{Heading} title="My Title" />'))
    return result

Children As Props#

If your template has children inside that tag, your component can ask for them as an argument, then place them as a variable:

def Heading(children, title):
    """The default heading."""
    return html("<h1>{title}</h1><div>{children}</div>")


def main() -> str:
    """Main entry point."""
    result = render(html('<{Heading} title="My Title">Child<//>'))
    return result

children is a keyword argument that is available to components. Note how the component closes with <//> when it contains nested children, as opposed to the self-closing form in the first example.

Expressions as Prop Values#

The “prop” can also be a Python symbol, using curly braces as the attribute value:

def Heading(title):
    """The default heading."""
    return html("<h1>{title}</h1>")


def main() -> str:
    """Main entry point."""
    result = render(html('<{Heading} title={"My Title"} />'))
    return result

Prop Values from Scope Variables#

That prop value can also be an in-scope variable:

def Heading(title):
    """The default heading."""
    return html("<h1>{title}</h1>")


this_title = "My Title"


def main() -> str:
    """Main entry point."""
    result = render(html("<{Heading} title={this_title} />"))
    return result

Optional Props#

Since this is typical function-argument stuff, you can have optional props through argument defaults:

def Heading(title="My Title"):
    """The default heading."""
    return html("<h1>{title}</h1>")


def main() -> str:
    """Main entry point."""
    result = render(html("<{Heading} />"))
    return result

Spread Props#

Sometimes you just want to pass everything in a dict as props. In JS, this is known as the “spread operator” and is supported:

def Heading(title, this_id):
    """The default heading."""
    return html("<div title={title} id={this_id}>Hello</div>")


def main() -> str:
    """Main entry point."""
    props = dict(title="My Title", this_id="d1")
    result = render(html("<{Heading} ...{props}>Child<//>"))
    return result

Pass Component as Prop#

Here’s a useful pattern: you can pass a component as a “prop” to another component. This lets the caller – in this case, the result line – do the driving:

def DefaultHeading():
    """The default heading."""
    return html("<h1>Default Heading</h1>")


def Body(heading):
    """The body which renders the heading."""
    return html("<body><{heading} /></body>")


def main() -> str:
    """Main entry point."""
    result = render(html("<{Body} heading={DefaultHeading} />"))
    return result

Default Component for Prop#

As a variation, let the caller do the driving but make the prop default to a default component if none was provided:

def DefaultHeading():  # pragma: nocover
    """The default heading."""
    return html("<h1>Default Heading</h1>")


def OtherHeading():
    """Another heading used in another condition."""
    return html("<h1>Other Heading</h1>")


def Body(heading=DefaultHeading):
    """Render the body with a heading based on which is passed in."""
    return html("<body><{heading} /></body>")


def main() -> str:
    """Main entry point."""
    result = render(html("<{Body} heading={OtherHeading}/>"))
    return result

Conditional Default#

One final variation for passing a component as a prop… move the “default or passed-in” decision into the template itself:

def DefaultHeading():
    """The default heading."""
    return html("<h1>Default Heading</h1>")


def OtherHeading():
    """Another heading used in another condition."""
    return html("<h1>Other Heading</h1>")


def Body(heading=None):
    """Render the body with a heading based on which is passed in."""
    return html("<body>{heading if heading else DefaultHeading}</body>")


def main() -> str:
    """Main entry point."""
    result = render(html("<{Body} heading={OtherHeading}/>"))
    return result

Children as Prop#

You can combine different props and arguments. In this case, title is a prop. children is another argument, but is provided automatically by render.

def Heading(children, title):
    """The default heading."""
    return html("<h1>{title}</h1><div>{children}</div>")


def main() -> str:
    """Main entry point."""
    result = render(html('<{Heading} title="My Title">Child<//>'))
    return result

Generators as Components#

You can also have components that act as generators. For example, imagine you have a todo list. There might be a lot of todos, so you want to generate them in a memory-efficient way:

def Todos():
    """A sequence of li items."""
    for todo in ["First", "Second"]:  # noqa B007
        yield html("<li>{todo}</li>")


def main() -> str:
    """Main entry point."""
    result = render(html("<ul><{Todos}/></ul>"))
    return result

Subcomponents#

Subcomponents are also feasible. They make up part of both the VDOM and the rendering:

def Todo(label):
    """An individual to do component."""
    return html("<li>{label}</li>")


def TodoList(todos):
    """A to do list component."""
    return html("<ul>{[Todo(label) for label in todos]}</ul>")


def main() -> str:
    """Main entry point."""
    todos = ["first"]
    return render(
        html(
            """
      <h1>{title}</h1>
      <{TodoList} todos={todos} />
    """
        )
    )

Architectural Note#

Components and subcomponents are a useful feature to users of some UI layer, as well as creators of that layer. They are also, though, an interesting architectural plug point.

As render walks through a VDOM, a usage of a component pops up with the props and children. But it isn’t yet the rendered component. The callable…hasn’t been called.

It’s the job of render to do so. If you look at the code for render and the utilities it uses, it’s not a lot of code. It’s reasonable to write your own, which is what some of the integrations have done.

This becomes an interesting place to experiment with your own component policies. Want a cache layer? Want to log each call? Maybe type validation? Want to (like the wired integration) write a custom DI system that gets argument values from special locations (e.g. database queries)?

Lots of possibilities, especially since the surface area is small enough and easy enough to play around.