html.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright 2014 Manu Martinez-Almeida. All rights reserved.
  2. // Use of this source code is governed by a MIT style
  3. // license that can be found in the LICENSE file.
  4. package render
  5. import (
  6. "html/template"
  7. "net/http"
  8. )
  9. type (
  10. HTMLRender interface {
  11. Instance(string, interface{}) Render
  12. }
  13. HTMLProduction struct {
  14. Template *template.Template
  15. }
  16. HTMLDebug struct {
  17. Files []string
  18. Glob string
  19. }
  20. HTML struct {
  21. Template *template.Template
  22. Name string
  23. Data interface{}
  24. }
  25. )
  26. var htmlContentType = []string{"text/html; charset=utf-8"}
  27. func (r HTMLProduction) Instance(name string, data interface{}) Render {
  28. return HTML{
  29. Template: r.Template,
  30. Name: name,
  31. Data: data,
  32. }
  33. }
  34. func (r HTMLDebug) Instance(name string, data interface{}) Render {
  35. return HTML{
  36. Template: r.loadTemplate(),
  37. Name: name,
  38. Data: data,
  39. }
  40. }
  41. func (r HTMLDebug) loadTemplate() *template.Template {
  42. if len(r.Files) > 0 {
  43. return template.Must(template.ParseFiles(r.Files...))
  44. }
  45. if len(r.Glob) > 0 {
  46. return template.Must(template.ParseGlob(r.Glob))
  47. }
  48. panic("the HTML debug render was created without files or glob pattern")
  49. }
  50. func (r HTML) Render(w http.ResponseWriter) error {
  51. writeContentType(w, htmlContentType)
  52. if len(r.Name) == 0 {
  53. return r.Template.Execute(w, r.Data)
  54. }
  55. return r.Template.ExecuteTemplate(w, r.Name, r.Data)
  56. }