Property Inheritance #1088
-
I am looking for a way to make a property defined on a parent component available to a children component without having to pass it in as template property at both levels. For instance:
Output:
My initial thought was "you can do this by abusing context". Something like this:
This doesn't work as Is this sort of abuse of context possible? Or is there another way to make this sort of property inheritance work? Ideally this would work something like ContextProviders do in the React world. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
I believe you could use some go code for this purpose: templ Field(isRequired bool) {
{{ ctx = context.WithValue(ctx, "isRequired", isRequired) }}
<div class="field">{ children... }</div>
} I'd recommend "prop-drilling" instead though, but that is a personal opinion. |
Beta Was this translation helpful? Give feedback.
There's a section in the docs about it: https://templ.guide/syntax-and-usage/context/#prop-drilling
Don't forget that templ components are just Go code that has a Render method. You could probably implement a context provider component that sets the value and renders children, passing the context.
There's some examples of code components like templ.Once or templ.Flush and you should see how you can make a context setter.