diff --git a/docs/docs/03-syntax-and-usage/10-template-composition.md b/docs/docs/03-syntax-and-usage/10-template-composition.md index cd869b69e..e9d0f3b23 100644 --- a/docs/docs/03-syntax-and-usage/10-template-composition.md +++ b/docs/docs/03-syntax-and-usage/10-template-composition.md @@ -64,6 +64,81 @@ The use of the `{ children... }` expression in the child component. ``` +### 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() { +
+ { children... } +
+} + +func main() { + contents := templ.ComponentFunc(func(ctx context.Context, w io.Writer) error { + _, err := io.WriteString(w, "
Inserted from Go code
") + return err + }) + ctx := templ.WithChildren(context.Background(), contents) + wrapChildren().Render(ctx, os.Stdout) +} +``` + +```html title="output" +
+
+ Inserted from Go code +
+
+``` + +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, "
Inserted from Go code
") + 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, "
") + if err != nil { + return err + } + err = children.Render(ctx, w) + if err != nil { + return err + } + _, err = io.WriteString(w, "
") + 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.