From 822d11a465aa640634789dd39babb14220f887eb Mon Sep 17 00:00:00 2001 From: toimtoimtoim Date: Sun, 20 Oct 2024 20:59:39 +0300 Subject: [PATCH] Add TemplateRenderer struct to ease creating renderers for `html/template` and `text/template` packages. --- echo.go | 6 ------ renderer.go | 29 +++++++++++++++++++++++++++++ renderer_test.go | 28 ++++++++++++++++++++++++++++ 3 files changed, 57 insertions(+), 6 deletions(-) create mode 100644 renderer.go create mode 100644 renderer_test.go diff --git a/echo.go b/echo.go index dbb98113a..2d7d5bb8d 100644 --- a/echo.go +++ b/echo.go @@ -45,7 +45,6 @@ import ( "encoding/json" "errors" "fmt" - "io" stdLog "log" "net" "net/http" @@ -142,11 +141,6 @@ type JSONSerializer interface { Deserialize(c Context, i interface{}) error } -// Renderer is the interface that wraps the Render function. -type Renderer interface { - Render(io.Writer, string, interface{}, Context) error -} - // Map defines a generic map of type `map[string]interface{}`. type Map map[string]interface{} diff --git a/renderer.go b/renderer.go new file mode 100644 index 000000000..44e038f35 --- /dev/null +++ b/renderer.go @@ -0,0 +1,29 @@ +package echo + +import "io" + +// Renderer is the interface that wraps the Render function. +type Renderer interface { + Render(io.Writer, string, interface{}, Context) error +} + +// TemplateRenderer is helper to ease creating renderers for `html/template` and `text/template` packages. +// Example usage: +// +// e.Renderer = &echo.TemplateRenderer{ +// Template: template.Must(template.ParseGlob("templates/*.html")), +// } +// +// e.Renderer = &echo.TemplateRenderer{ +// Template: template.Must(template.New("hello").Parse("Hello, {{.}}!")), +// } +type TemplateRenderer struct { + Template interface { + ExecuteTemplate(wr io.Writer, name string, data any) error + } +} + +// Render renders the template with given data. +func (t *TemplateRenderer) Render(w io.Writer, name string, data interface{}, c Context) error { + return t.Template.ExecuteTemplate(w, name, data) +} diff --git a/renderer_test.go b/renderer_test.go new file mode 100644 index 000000000..ad37a5552 --- /dev/null +++ b/renderer_test.go @@ -0,0 +1,28 @@ +package echo + +import ( + "github.com/stretchr/testify/assert" + "html/template" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestRenderWithTemplateRenderer(t *testing.T) { + e := New() + req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(userJSON)) + rec := httptest.NewRecorder() + + c := e.NewContext(req, rec) + + e.Renderer = &TemplateRenderer{ + Template: template.Must(template.New("hello").Parse("Hello, {{.}}!")), + } + + err := c.Render(http.StatusOK, "hello", "Jon Snow") + if assert.NoError(t, err) { + assert.Equal(t, http.StatusOK, rec.Code) + assert.Equal(t, "Hello, Jon Snow!", rec.Body.String()) + } +}