ginpongo2/render.go

62 lines
1.2 KiB
Go
Raw Normal View History

2020-03-19 20:56:38 +01:00
package ginpongo2
import (
"fmt"
"net/http"
2020-03-19 21:00:34 +01:00
"strings"
2020-03-19 20:56:38 +01:00
"github.com/flosch/pongo2"
"github.com/gin-gonic/gin/render"
)
var Suffix = ".html.twig"
type Pongo struct {
set *pongo2.TemplateSet
basedir string
}
func (p *Pongo) Instance(name string, data interface{}) render.Render {
r := new(PongoRenderer)
tpl, e := p.set.FromCache(fmt.Sprintf("%s%s%s", p.basedir, name, Suffix))
if e != nil {
panic(e)
}
r.tpl = tpl
r.data = data
return r
}
type PongoRenderer struct {
tpl *pongo2.Template
data interface{}
}
func (r *PongoRenderer) Render(w http.ResponseWriter) error {
if r.data == nil {
r.data = make(pongo2.Context)
}
d := r.data.(pongo2.Context)
return r.tpl.ExecuteWriter(d, w)
}
func (r *PongoRenderer) WriteContentType(w http.ResponseWriter) {
if v := w.Header().Get("content-type"); len(v) == 0 {
w.Header().Set("content-type", "text/html; charset=utf8")
}
}
2020-03-19 21:10:06 +01:00
func New(basedir string, debug bool, loaders ...pongo2.TemplateLoader) *Pongo {
2020-03-19 20:56:38 +01:00
p := new(Pongo)
p.set = pongo2.NewSet("html")
p.set.Debug = debug
2020-03-19 21:00:34 +01:00
if !strings.HasSuffix(basedir, "/") {
basedir = basedir + "/"
}
2020-03-19 20:56:38 +01:00
p.basedir = basedir
2020-03-19 21:10:06 +01:00
if len(loaders) > 0 {
p.set.AddLoader(loaders...)
}
2020-03-19 20:56:38 +01:00
return p
}