html.go 1.7 KB

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