[go: up one dir, main page]

Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Setting children from go code #909

Closed
rotemhoresh opened this issue Sep 7, 2024 · 2 comments
Closed

Setting children from go code #909

rotemhoresh opened this issue Sep 7, 2024 · 2 comments
Labels
docs question Further information is requested

Comments

@rotemhoresh
Copy link

The title basically, e.g.:

// comp.templ
templ Comp() {
    <div class="error">
        { children... }
    </div>
}
// render.go
Comp().Render(ctx, w)  // how to set children components / raw HTML from here?
@a-h
Copy link
Owner
a-h commented Sep 8, 2024

To pass children in code, you can use the templ.WithChildren function to create a context that has children:

ctx := templ.WithChildren(ctx, child)
err := Comp().Render(ctx, sb)

The inverse (getting the children from within Go code) is done with the templ.GetChildren function.

templ/runtime.go

Lines 60 to 82 in e2511cd

func WithChildren(ctx context.Context, children Component) context.Context {
ctx, v := getContext(ctx)
v.children = &children
return ctx
}
func ClearChildren(ctx context.Context) context.Context {
_, v := getContext(ctx)
v.children = nil
return ctx
}
// NopComponent is a component that doesn't render anything.
var NopComponent = ComponentFunc(func(ctx context.Context, w io.Writer) error { return nil })
// GetChildren from the context.
func GetChildren(ctx context.Context) Component {
_, v := getContext(ctx)
if v.children == nil {
return NopComponent
}
return *v.children
}

There can only actually be one child. We haven't (currently) got an API to concatenate multiple templ components into a single component. The consensus is that adding templ.Join to do that would be useful, as per #788

That way, you could have templ.WithChildren(ctx, templ.Join(childA, childB, childC)) although, we'd probably update templ.WithChildren to take a variadic param, so you could do templ.WithChildren(ctx, childA, childB, childC) and do the templ.Join inside the function call.

@linear linear bot added question Further information is requested docs labels Sep 8, 2024
@a-h a-h closed this as completed in 5044001 Sep 8, 2024
@a-h
Copy link
Owner
a-h commented Sep 8, 2024

I've updated the docs to include this information. Feel free to re-open etc. if needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
docs question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants