template service: add Render() method
This commit is contained in:
parent
42aba649c8
commit
636b2dbf8f
@ -1,6 +1,7 @@
|
||||
package template
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
@ -13,6 +14,7 @@ const ServiceName service.Name = "template"
|
||||
// Service is a templating service
|
||||
type Service interface {
|
||||
RenderPage(w http.ResponseWriter, templateName string, data interface{}) error
|
||||
Render(w io.Writer, templateName string, data interface{}) error
|
||||
}
|
||||
|
||||
// From retrieves the template service in the given container
|
||||
|
@ -3,6 +3,7 @@ package html
|
||||
import (
|
||||
"fmt"
|
||||
"html/template"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
@ -102,6 +103,28 @@ func (t *TemplateService) RenderPage(w http.ResponseWriter, templateName string,
|
||||
|
||||
}
|
||||
|
||||
// Render renders a template to the given io.Writer
|
||||
func (t *TemplateService) Render(w io.Writer, templateName string, data interface{}) error {
|
||||
|
||||
// Ensure the template exists in the map.
|
||||
tmpl, ok := t.templates[templateName]
|
||||
if !ok {
|
||||
return fmt.Errorf("the template '%s' does not exist", templateName)
|
||||
}
|
||||
|
||||
// Create a buffer to temporarily write to and check if any errors were encountered.
|
||||
buf := t.pool.Get()
|
||||
defer t.pool.Put(buf)
|
||||
|
||||
if err := tmpl.ExecuteTemplate(buf, templateName, data); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err := buf.WriteTo(w)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// NewTemplateService returns a new Service
|
||||
func NewTemplateService(funcs ...OptionFunc) *TemplateService {
|
||||
options := defaultOptions()
|
||||
|
Loading…
Reference in New Issue
Block a user