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:
parent
d5b32c6e47
commit
822d11a465
6
echo.go
6
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{}
|
||||
|
||||
|
29
renderer.go
Normal file
29
renderer.go
Normal 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
28
renderer_test.go
Normal 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())
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user