Skip to content

Commit

Permalink
Add hx-on (#10)
Browse files Browse the repository at this point in the history
Fixes #9
  • Loading branch information
markuswustenberg authored Oct 4, 2023
2 parents 66db7e0 + cadd169 commit 1e64832
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
23 changes: 23 additions & 0 deletions htmx.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
package htmx

import (
"io"

g "github.com/maragudk/gomponents"
)

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

// On handles any event with a script inline.
// See https://htmx.org/attributes/hx-on
func On(name string, v string) g.Node {
return &rawAttr{name: "on:" + name, value: v}
}

// Post to the specified URL.
// See https://htmx.org/attributes/hx-post
func Post(url string) g.Node {
Expand Down Expand Up @@ -195,3 +203,18 @@ func Validate(v string) g.Node {
func attr(name, value string) g.Node {
return g.Attr("hx-"+name, value)
}

// rawAttr is an attribute that doesn't escape its value.
type rawAttr struct {
name string
value string
}

func (r *rawAttr) Render(w io.Writer) error {
_, err := w.Write([]byte(" hx-" + r.name + `="` + r.value + `"`))
return err
}

func (r *rawAttr) Type() g.NodeType {
return g.AttributeType
}
12 changes: 12 additions & 0 deletions htmx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,15 @@ func ExampleGet() {
_ = n.Render(os.Stdout)
// Output: <button hx-post="/clicked" hx-swap="outerHTML"></button>
}

func TestOn(t *testing.T) {
t.Run(`should output hx-on:click="alert('hat')"`, func(t *testing.T) {
n := g.El("div", hx.On("click", "alert('hat')"))
assert.Equal(t, `<div hx-on:click="alert('hat')"></div>`, n)
})

t.Run(`should output hx-on::before-request="alert('hat')"`, func(t *testing.T) {
n := g.El("div", hx.On(":before-request", "alert('hat')"))
assert.Equal(t, `<div hx-on::before-request="alert('hat')"></div>`, n)
})
}

0 comments on commit 1e64832

Please sign in to comment.