From f27cb0c05f23785189979e57c831eb798e1da1f1 Mon Sep 17 00:00:00 2001 From: Markus Wüstenberg Date: Wed, 23 Sep 2020 22:10:35 +0200 Subject: Add Textf function (#17) Like Text, but calls fmt.Sprintf before rendering.--- README.md | 2 +- gomponents.go | 7 +++++++ gomponents_test.go | 7 +++++++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index b817ad0..23b29b7 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,7 @@ func Page(title, path string) g.Node { el.Body( Navbar(path), el.H1(title), - el.P(g.Text(fmt.Sprintf("Welcome to the page at %v.", path))), + el.P(g.Textf("Welcome to the page at %v.", path)), ), ), ) diff --git a/gomponents.go b/gomponents.go index d160b54..21d3e75 100644 --- a/gomponents.go +++ b/gomponents.go @@ -109,6 +109,13 @@ func Text(t string) NodeFunc { } } +// Textf creates a text DOM Node that Renders the interpolated and escaped string t. +func Textf(format string, a ...interface{}) NodeFunc { + return func() string { + return template.HTMLEscaper(fmt.Sprintf(format, a...)) + } +} + // Raw creates a raw Node that just Renders the unescaped string t. func Raw(t string) NodeFunc { return func() string { diff --git a/gomponents_test.go b/gomponents_test.go index 78b69f0..ee0b91d 100644 --- a/gomponents_test.go +++ b/gomponents_test.go @@ -81,6 +81,13 @@ func TestText(t *testing.T) { }) } +func TestTextf(t *testing.T) { + t.Run("renders interpolated and escaped text", func(t *testing.T) { + e := g.Textf("<%v/>", "div") + assert.Equal(t, "<div/>", e) + }) +} + func TestRaw(t *testing.T) { t.Run("renders raw text", func(t *testing.T) { e := g.Raw("
") -- cgit 1.4.1