Skip to content

Commit

Permalink
docs: document use of children in code components, closes #909
Browse files Browse the repository at this point in the history
  • Loading branch information
a-h committed Sep 8, 2024
1 parent e2511cd commit 5044001
Showing 1 changed file with 75 additions and 0 deletions.
75 changes: 75 additions & 0 deletions docs/docs/03-syntax-and-usage/10-template-composition.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,81 @@ The use of the `{ children... }` expression in the child component.
</div>
```

### Using children in code components

Children are passed to a component using the Go context. To pass children to a component using Go code, use the `templ.WithChildren` function.

```templ
package main
import (
"context"
"os"
"github.com/a-h/templ"
)
templ wrapChildren() {
<div id="wrapper">
{ children... }
</div>
}
func main() {
contents := templ.ComponentFunc(func(ctx context.Context, w io.Writer) error {
_, err := io.WriteString(w, "<div>Inserted from Go code</div>")
return err
})
ctx := templ.WithChildren(context.Background(), contents)
wrapChildren().Render(ctx, os.Stdout)
}
```

```html title="output"
<div id="wrapper">
<div>
Inserted from Go code
</div>
</div>
```

To get children from the context, use the `templ.GetChildren` function.

```templ
package main
import (
"context"
"os"
"github.com/a-h/templ"
)
func main() {
contents := templ.ComponentFunc(func(ctx context.Context, w io.Writer) error {
_, err := io.WriteString(w, "<div>Inserted from Go code</div>")
return err
})
wrapChildren := templ.ComponentFunc(func(ctx context.Context, w io.Writer) error {
children := templ.GetChildren(ctx)
ctx = templ.ClearChildren(ctx)
_, err := io.WriteString(w, "<div id=\"wrapper\">")
if err != nil {
return err
}
err = children.Render(ctx, w)
if err != nil {
return err
}
_, err = io.WriteString(w, "</div>")
return err
})
```

:::note
The `templ.ClearChildren` function is used to stop passing the children down the tree.
:::

## Components as parameters

Components can also be passed as parameters and rendered using the `@component` expression.
Expand Down

0 comments on commit 5044001

Please sign in to comment.