Index
Dash Compose provides a tidier way of composing Plotly Dash layouts. Read about the motivation behind it here, and install it from PyPI with
pip install dash-compose
Hello world!
The code below is a complete Dash application, in which Dash Compose has been used to create a small tree of Dash components for the application's layout.
| hello_world.py | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |
When rendered as HTML, this looks like
<div>
<span>Hello </span>
<span>world!</span>
</div>
Let's step through the layout portion of the example and see what's going on.
Compositions
6 7 8 9 10 11 12 | |
Compositions are created by decorating a function, in this case hello_world, with @composition.
There are no restrictions on the kinds of inputs this function takes, or on the outputs it returns.
The role of the @composition decorator is only to instantiate the parent-child relationships that your function describes.
Here, our function takes no inputs, and returns one output.
Context managers
6 7 8 9 10 11 12 | |
Within your function you can use Dash components as context-managers.
This specifies that they will be the parent in one or more parent-child relationship.
To specify a child in that relationship, you can use the yield statement after the context has been entered.
Within a component's context, you can have multiple yield statements, or indeed any Python code you like.
Here, we have yielded a Span within a Div, so the Span becomes a child of the Div.
Nested contexts
6 7 8 9 10 11 12 | |
Nesting context managers is another way you can specify a parent-child relationship.
In this case, the Span managing the inner context will become a child of the Div managing the outer context.
6 7 8 9 10 11 12 | |
When you have nested context managers, yield statements will create parent-child relationships based on the most recently entered context.
In this case, "world!" becomes a child of Span, and only has an indirect (grand-parent) relationship with the outer Div.
Note here that we have yielded something that isn't a Dash component!
This is fine: You are able to yield any Python object that is a valid child of a Dash component.