render.go 1021 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package ginpongo2
  2. import (
  3. "fmt"
  4. "net/http"
  5. "github.com/flosch/pongo2/v4"
  6. "github.com/gin-gonic/gin/render"
  7. )
  8. var Suffix = ".html.twig"
  9. type Pongo struct {
  10. set *pongo2.TemplateSet
  11. }
  12. func (p *Pongo) Instance(name string, data interface{}) render.Render {
  13. r := new(PongoRenderer)
  14. tpl, e := p.set.FromCache(fmt.Sprintf("%s%s", name, Suffix))
  15. if e != nil {
  16. panic(e)
  17. }
  18. r.tpl = tpl
  19. r.data = data
  20. return r
  21. }
  22. type PongoRenderer struct {
  23. tpl *pongo2.Template
  24. data interface{}
  25. }
  26. func (r *PongoRenderer) Render(w http.ResponseWriter) error {
  27. if r.data == nil {
  28. r.data = make(pongo2.Context)
  29. }
  30. d := r.data.(pongo2.Context)
  31. return r.tpl.ExecuteWriter(d, w)
  32. }
  33. func (r *PongoRenderer) WriteContentType(w http.ResponseWriter) {
  34. if v := w.Header().Get("content-type"); len(v) == 0 {
  35. w.Header().Set("content-type", "text/html; charset=utf8")
  36. }
  37. }
  38. func New(debug bool, loaders ...pongo2.TemplateLoader) *Pongo {
  39. p := new(Pongo)
  40. p.set = pongo2.NewSet("html", loaders...)
  41. p.set.Debug = debug
  42. return p
  43. }