53 lines
1019 B
Go
53 lines
1019 B
Go
package ginpongo2v3
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin/render"
|
|
"gopkg.in/flosch/pongo2.v3"
|
|
)
|
|
|
|
var Suffix = ".html.twig"
|
|
|
|
type Pongo struct {
|
|
set *pongo2.TemplateSet
|
|
}
|
|
|
|
func (p *Pongo) Instance(name string, data interface{}) render.Render {
|
|
r := new(PongoRenderer)
|
|
tpl, e := p.set.FromCache(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 := pongo2.Context(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")
|
|
}
|
|
}
|
|
|
|
func New(name, basepath string, debug bool) *Pongo {
|
|
p := new(Pongo)
|
|
p.set = pongo2.NewSet(name)
|
|
p.set.Debug = debug
|
|
p.set.SetBaseDirectory(basepath)
|
|
return p
|
|
}
|