Skip to content

Commit

Permalink
Add Rawf (#114)
Browse files Browse the repository at this point in the history
Like `Raw`, but interpolates like `Textf`.
  • Loading branch information
markuswustenberg authored Nov 3, 2022
1 parent 34df17d commit 3bb4e3e
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
12 changes: 10 additions & 2 deletions gomponents.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
// to the given writer as a string.
//
// All DOM elements and attributes can be created by using the El and Attr functions.
// The functions Text, Textf, and Raw can be used to create text nodes.
// The functions Text, Textf, Raw, and Rawf can be used to create text nodes.
// See also helper functions Group, Map, and If.
//
// For basic HTML elements and attributes, see the package html.
Expand Down Expand Up @@ -207,7 +207,7 @@ func Text(t string) Node {
})
}

// Textf creates a text DOM Node that Renders the interpolated and escaped string t.
// Textf creates a text DOM Node that Renders the interpolated and escaped string format.
func Textf(format string, a ...interface{}) Node {
return NodeFunc(func(w io.Writer) error {
_, err := w.Write([]byte(template.HTMLEscapeString(fmt.Sprintf(format, a...))))
Expand All @@ -223,6 +223,14 @@ func Raw(t string) Node {
})
}

// Rawf creates a text DOM Node that just Renders the interpolated and unescaped string format.
func Rawf(format string, a ...interface{}) Node {
return NodeFunc(func(w io.Writer) error {
_, err := w.Write([]byte(fmt.Sprintf(format, a...)))
return err
})
}

type group struct {
children []Node
}
Expand Down
15 changes: 15 additions & 0 deletions gomponents_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,21 @@ func ExampleRaw() {
// Output: <span><button onclick="javascript:alert('Party time!')">Party hats</button> &gt; normal hats.</span>
}

func TestRawf(t *testing.T) {
t.Run("renders interpolated and raw text", func(t *testing.T) {
e := g.Rawf("<%v>", "div")
assert.Equal(t, "<div>", e)
})
}

func ExampleRawf() {
e := g.El("span",
g.Rawf(`<button onclick="javascript:alert('%v')">Party hats</button> &gt; normal hats.`, "Party time!"),
)
_ = e.Render(os.Stdout)
// Output: <span><button onclick="javascript:alert('Party time!')">Party hats</button> &gt; normal hats.</span>
}

func TestGroup(t *testing.T) {
t.Run("groups multiple nodes into one", func(t *testing.T) {
children := []g.Node{g.El("br", g.Attr("id", "hat")), g.El("hr")}
Expand Down

0 comments on commit 3bb4e3e

Please sign in to comment.