Skip to content

Commit 1e64832

Browse files
Add hx-on (#10)
Fixes #9
2 parents 66db7e0 + cadd169 commit 1e64832

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

htmx.go

+23
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
package htmx
44

55
import (
6+
"io"
7+
68
g "github.com/maragudk/gomponents"
79
)
810

@@ -18,6 +20,12 @@ func Get(url string) g.Node {
1820
return attr("get", url)
1921
}
2022

23+
// On handles any event with a script inline.
24+
// See https://htmx.org/attributes/hx-on
25+
func On(name string, v string) g.Node {
26+
return &rawAttr{name: "on:" + name, value: v}
27+
}
28+
2129
// Post to the specified URL.
2230
// See https://htmx.org/attributes/hx-post
2331
func Post(url string) g.Node {
@@ -195,3 +203,18 @@ func Validate(v string) g.Node {
195203
func attr(name, value string) g.Node {
196204
return g.Attr("hx-"+name, value)
197205
}
206+
207+
// rawAttr is an attribute that doesn't escape its value.
208+
type rawAttr struct {
209+
name string
210+
value string
211+
}
212+
213+
func (r *rawAttr) Render(w io.Writer) error {
214+
_, err := w.Write([]byte(" hx-" + r.name + `="` + r.value + `"`))
215+
return err
216+
}
217+
218+
func (r *rawAttr) Type() g.NodeType {
219+
return g.AttributeType
220+
}

htmx_test.go

+12
Original file line numberDiff line numberDiff line change
@@ -60,3 +60,15 @@ func ExampleGet() {
6060
_ = n.Render(os.Stdout)
6161
// Output: <button hx-post="/clicked" hx-swap="outerHTML"></button>
6262
}
63+
64+
func TestOn(t *testing.T) {
65+
t.Run(`should output hx-on:click="alert('hat')"`, func(t *testing.T) {
66+
n := g.El("div", hx.On("click", "alert('hat')"))
67+
assert.Equal(t, `<div hx-on:click="alert('hat')"></div>`, n)
68+
})
69+
70+
t.Run(`should output hx-on::before-request="alert('hat')"`, func(t *testing.T) {
71+
n := g.El("div", hx.On(":before-request", "alert('hat')"))
72+
assert.Equal(t, `<div hx-on::before-request="alert('hat')"></div>`, n)
73+
})
74+
}

0 commit comments

Comments
 (0)