Browse Source

template service: add Render() method

extension
wpetit 2 years ago
parent
commit
636b2dbf8f
2 changed files with 25 additions and 0 deletions
  1. +2
    -0
      service/template/service.go
  2. +23
    -0
      template/html/service.go

+ 2
- 0
service/template/service.go View File

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


+ 23
- 0
template/html/service.go View File

@ -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…
Cancel
Save