html.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. Delims struct {
  11. Left string
  12. Right string
  13. }
  14. HTMLRender interface {
  15. Instance(string, interface{}) Render
  16. }
  17. HTMLProduction struct {
  18. Template *template.Template
  19. Delims Delims
  20. }
  21. HTMLDebug struct {
  22. Files []string
  23. Glob string
  24. Delims Delims
  25. }
  26. HTML struct {
  27. Template *template.Template
  28. Name string
  29. Data interface{}
  30. }
  31. )
  32. var htmlContentType = []string{"text/html; charset=utf-8"}
  33. func (r HTMLProduction) Instance(name string, data interface{}) Render {
  34. return HTML{
  35. Template: r.Template,
  36. Name: name,
  37. Data: data,
  38. }
  39. }
  40. func (r HTMLDebug) Instance(name string, data interface{}) Render {
  41. return HTML{
  42. Template: r.loadTemplate(),
  43. Name: name,
  44. Data: data,
  45. }
  46. }
  47. func (r HTMLDebug) loadTemplate() *template.Template {
  48. if len(r.Files) > 0 {
  49. return template.Must(template.New("").Delims(r.Delims.Left, r.Delims.Right).ParseFiles(r.Files...))
  50. }
  51. if len(r.Glob) > 0 {
  52. return template.Must(template.New("").Delims(r.Delims.Left, r.Delims.Right).ParseGlob(r.Glob))
  53. }
  54. panic("the HTML debug render was created without files or glob pattern")
  55. }
  56. func (r HTML) Render(w http.ResponseWriter) error {
  57. r.WriteContentType(w)
  58. if len(r.Name) == 0 {
  59. return r.Template.Execute(w, r.Data)
  60. }
  61. return r.Template.ExecuteTemplate(w, r.Name, r.Data)
  62. }
  63. func (r HTML) WriteContentType(w http.ResponseWriter) {
  64. writeContentType(w, htmlContentType)
  65. }