Templ methods
#805
-
Recently I found out that templ function can be used as a method. type Button struct {}
templ (b Button) Render() {
<button>{children...}</button>
} templ SomeView() {
@Button{}.Render() { click me }
} So I went this way and come up with this: type button struct {
class string
attrs templ.Attributes
}
func Button() *button {
return &button {
class: "some_button_classes",
attrs: templ.Attributes{},
}
}
func (b *button) XL() *button {
b.class += " xl" // just an example
return b
}
func (b *button) Set(k string, v interface{}) *button {
b.attrs[k] = v
return b
}
templ (b *button) Render() {
<button { b.attrs... } class={b.class}>{children...}</button>
} templ SomeView() {
@Button().XL().Set("onclick", "alert('clicked')").Render() { click me }
} My question is - is there a way to get rid of .Render() call? And the second one: is there a way of writing method call on a new line? templ SomeView() {
@Button(). // getting "expected selector or type assertion, found '.' "
XL().
Set("onclick", "alert('clicked')").
Render() { click me }
} |
Beta Was this translation helpful? Give feedback.
Answered by
joerdav
Jun 24, 2024
Replies: 1 comment 1 reply
-
On the first point, you would need to implement the component interface to remove the need for
On the second point that seems to be a parsing bug, I would expect that to work. |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
tim-rus
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
On the first point, you would need to implement the component interface to remove the need for
Render()
. It is a bit more code but should have the desired effect.