html.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package render
  2. import (
  3. "html/template"
  4. "net/http"
  5. )
  6. type (
  7. HTMLRender interface {
  8. Instance(string, interface{}) Render
  9. }
  10. HTMLProduction struct {
  11. Template *template.Template
  12. }
  13. HTMLDebug struct {
  14. Files []string
  15. Glob string
  16. }
  17. HTML struct {
  18. Template *template.Template
  19. Name string
  20. Data interface{}
  21. }
  22. )
  23. func (r HTMLProduction) Instance(name string, data interface{}) Render {
  24. return HTML{
  25. Template: r.Template,
  26. Name: name,
  27. Data: data,
  28. }
  29. }
  30. func (r HTMLDebug) Instance(name string, data interface{}) Render {
  31. return HTML{
  32. Template: r.loadTemplate(),
  33. Name: name,
  34. Data: data,
  35. }
  36. }
  37. func (r HTMLDebug) loadTemplate() *template.Template {
  38. if len(r.Files) > 0 {
  39. return template.Must(template.ParseFiles(r.Files...))
  40. }
  41. if len(r.Glob) > 0 {
  42. return template.Must(template.ParseFiles(r.Files...))
  43. }
  44. panic("the HTML debug render was created without files or glob pattern")
  45. }
  46. func (r HTML) Write(w http.ResponseWriter) error {
  47. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  48. return r.Template.ExecuteTemplate(w, r.Name, r.Data)
  49. }