1
0
mirror of https://github.com/labstack/echo.git synced 2025-01-01 22:09:21 +02:00

Add TemplateRenderer struct to ease creating renderers for html/template and text/template packages.

This commit is contained in:
toimtoimtoim 2024-10-20 20:59:39 +03:00 committed by Martti T.
parent d5b32c6e47
commit 822d11a465
3 changed files with 57 additions and 6 deletions

View File

@ -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{}

29
renderer.go Normal file
View File

@ -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
renderer_test.go Normal file
View File

@ -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())
}
}