Added docs for the new compose method

This commit is contained in:
Will McGugan
2023-02-26 10:34:30 +00:00
parent 5c2cf2960e
commit 9c1f6f7fad
3 changed files with 77 additions and 25 deletions

View File

@@ -159,7 +159,45 @@ In other words, we have a single row containing two columns.
```
You may be tempted to use many levels of nested utility containers in order to build advanced, grid-like layouts.
However, Textual comes with a more powerful mechanism for achieving this known as _grid layout_, which we'll discuss next.
However, Textual comes with a more powerful mechanism for achieving this known as _grid layout_, which we'll discuss below.
## Composing with context managers
In the previous section we've show how you add children to a container (such as `Horizontal` and `Vertical`) with positional arguments.
It's fine to do it this way, but Textual offers a simplified syntax using [context managers](https://docs.python.org/3/reference/datamodel.html#context-managers) which is generally easier to write and edit.
You can introduce a container using Python's `with` statement. Any widgets yielded within that block are added to the container's children.
Let's take the [utility containers](#utility-containers) example and update it to use the context manager approach.
=== "utility_containers_using_with.py"
Composing with context managers.
```python
--8<-- "docs/examples/guide/layout/utility_containers_using_with.py"
```
=== "utility_containers.py"
This is the original code.
```python
--8<-- "docs/examples/guide/layout/utility_containers.py"
```
=== "utility_containers.css"
```sass hl_lines="2"
--8<-- "docs/examples/guide/layout/utility_containers.css"
```
=== "Output"
```{.textual path="docs/examples/guide/layout/utility_containers_using_with.py"}
```
Note how the end result is the same, but the code with context managers is a little easer to read. It is up to you which method you want to use, and you can mix context managers with positional arguments if you like!
## Grid