Skip to content

Commit

Permalink
Add TemplateRenderer struct to ease creating renderers for `html/temp…
Browse files Browse the repository at this point in the history
…late` and `text/template` packages.
  • Loading branch information
aldas committed Oct 20, 2024
1 parent d5b32c6 commit 822d11a
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 6 deletions.
6 changes: 0 additions & 6 deletions echo.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ import (
"encoding/json"
"errors"
"fmt"
"io"
stdLog "log"
"net"
"net/http"
Expand Down Expand Up @@ -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{}

Expand Down
29 changes: 29 additions & 0 deletions renderer.go
Original file line number Diff line number Diff line change
@@ -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)
}
28 changes: 28 additions & 0 deletions renderer_test.go
Original file line number Diff line number Diff line change
@@ -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())
}
}

0 comments on commit 822d11a

Please sign in to comment.