amber.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. package view
  2. import (
  3. "fmt"
  4. "html/template"
  5. "io"
  6. "path/filepath"
  7. "strings"
  8. "sync"
  9. "github.com/eknkc/amber"
  10. )
  11. // AmberEngine contains the amber view engine structure.
  12. type AmberEngine struct {
  13. // files configuration
  14. directory string
  15. extension string
  16. assetFn func(name string) ([]byte, error) // for embedded, in combination with directory & extension
  17. namesFn func() []string // for embedded, in combination with directory & extension
  18. reload bool
  19. //
  20. rmu sync.RWMutex // locks for `ExecuteWiter` when `reload` is true.
  21. funcs map[string]interface{}
  22. templateCache map[string]*template.Template
  23. }
  24. var _ Engine = &AmberEngine{}
  25. // Amber creates and returns a new amber view engine.
  26. func Amber(directory, extension string) *AmberEngine {
  27. s := &AmberEngine{
  28. directory: directory,
  29. extension: extension,
  30. templateCache: make(map[string]*template.Template, 0),
  31. funcs: make(map[string]interface{}, 0),
  32. }
  33. return s
  34. }
  35. // Ext returns the file extension which this view engine is responsible to render.
  36. func (s *AmberEngine) Ext() string {
  37. return s.extension
  38. }
  39. // Binary optionally, use it when template files are distributed
  40. // inside the app executable (.go generated files).
  41. //
  42. // The assetFn and namesFn can come from the go-bindata library.
  43. func (s *AmberEngine) Binary(assetFn func(name string) ([]byte, error), namesFn func() []string) *AmberEngine {
  44. s.assetFn, s.namesFn = assetFn, namesFn
  45. return s
  46. }
  47. // Reload if setted to true the templates are reloading on each render,
  48. // use it when you're in development and you're boring of restarting
  49. // the whole app when you edit a template file.
  50. //
  51. // Note that if `true` is passed then only one `View -> ExecuteWriter` will be render each time,
  52. // no concurrent access across clients, use it only on development status.
  53. // It's good to be used side by side with the https://github.com/kataras/rizla reloader for go source files.
  54. func (s *AmberEngine) Reload(developmentMode bool) *AmberEngine {
  55. s.reload = developmentMode
  56. return s
  57. }
  58. // AddFunc adds the function to the template's function map.
  59. // It is legal to overwrite elements of the default actions:
  60. // - url func(routeName string, args ...string) string
  61. // - urlpath func(routeName string, args ...string) string
  62. // - render func(fullPartialName string) (template.HTML, error).
  63. func (s *AmberEngine) AddFunc(funcName string, funcBody interface{}) {
  64. s.rmu.Lock()
  65. s.funcs[funcName] = funcBody
  66. s.rmu.Unlock()
  67. }
  68. // Load parses the templates to the engine.
  69. // It's alos responsible to add the necessary global functions.
  70. //
  71. // Returns an error if something bad happens, user is responsible to catch it.
  72. func (s *AmberEngine) Load() error {
  73. if s.assetFn != nil && s.namesFn != nil {
  74. // embedded
  75. return s.loadAssets()
  76. }
  77. // load from directory, make the dir absolute here too.
  78. dir, err := filepath.Abs(s.directory)
  79. if err != nil {
  80. return err
  81. }
  82. // change the directory field configuration, load happens after directory has been setted, so we will not have any problems here.
  83. s.directory = dir
  84. return s.loadDirectory()
  85. }
  86. // loadDirectory loads the amber templates from directory.
  87. func (s *AmberEngine) loadDirectory() error {
  88. dir, extension := s.directory, s.extension
  89. opt := amber.DirOptions{}
  90. opt.Recursive = true
  91. // prepare the global amber funcs
  92. funcs := template.FuncMap{}
  93. for k, v := range amber.FuncMap { // add the amber's default funcs
  94. funcs[k] = v
  95. }
  96. for k, v := range s.funcs {
  97. funcs[k] = v
  98. }
  99. amber.FuncMap = funcs //set the funcs
  100. opt.Ext = extension
  101. templates, err := amber.CompileDir(dir, opt, amber.DefaultOptions) // this returns the map with stripped extension, we want extension so we copy the map
  102. if err == nil {
  103. s.templateCache = make(map[string]*template.Template)
  104. for k, v := range templates {
  105. name := filepath.ToSlash(k + opt.Ext)
  106. s.templateCache[name] = v
  107. delete(templates, k)
  108. }
  109. }
  110. return err
  111. }
  112. // loadAssets builds the templates by binary, embedded.
  113. func (s *AmberEngine) loadAssets() error {
  114. virtualDirectory, virtualExtension := s.directory, s.extension
  115. assetFn, namesFn := s.assetFn, s.namesFn
  116. // prepare the global amber funcs
  117. funcs := template.FuncMap{}
  118. for k, v := range amber.FuncMap { // add the amber's default funcs
  119. funcs[k] = v
  120. }
  121. for k, v := range s.funcs {
  122. funcs[k] = v
  123. }
  124. if len(virtualDirectory) > 0 {
  125. if virtualDirectory[0] == '.' { // first check for .wrong
  126. virtualDirectory = virtualDirectory[1:]
  127. }
  128. if virtualDirectory[0] == '/' || virtualDirectory[0] == filepath.Separator { // second check for /something, (or ./something if we had dot on 0 it will be removed
  129. virtualDirectory = virtualDirectory[1:]
  130. }
  131. }
  132. amber.FuncMap = funcs //set the funcs
  133. names := namesFn()
  134. for _, path := range names {
  135. if !strings.HasPrefix(path, virtualDirectory) {
  136. continue
  137. }
  138. ext := filepath.Ext(path)
  139. if ext == virtualExtension {
  140. rel, err := filepath.Rel(virtualDirectory, path)
  141. if err != nil {
  142. return err
  143. }
  144. buf, err := assetFn(path)
  145. if err != nil {
  146. return err
  147. }
  148. name := filepath.ToSlash(rel)
  149. tmpl, err := amber.CompileData(buf, name, amber.DefaultOptions)
  150. if err != nil {
  151. return err
  152. }
  153. s.templateCache[name] = tmpl
  154. }
  155. }
  156. return nil
  157. }
  158. func (s *AmberEngine) fromCache(relativeName string) *template.Template {
  159. tmpl, ok := s.templateCache[relativeName]
  160. if ok {
  161. return tmpl
  162. }
  163. return nil
  164. }
  165. // ExecuteWriter executes a template and writes its result to the w writer.
  166. // layout here is useless.
  167. func (s *AmberEngine) ExecuteWriter(w io.Writer, filename string, layout string, bindingData interface{}) error {
  168. // re-parse the templates if reload is enabled.
  169. if s.reload {
  170. // locks to fix #872, it's the simplest solution and the most correct,
  171. // to execute writers with "wait list", one at a time.
  172. s.rmu.Lock()
  173. defer s.rmu.Unlock()
  174. if err := s.Load(); err != nil {
  175. return err
  176. }
  177. }
  178. if tmpl := s.fromCache(filename); tmpl != nil {
  179. return tmpl.Execute(w, bindingData)
  180. }
  181. return fmt.Errorf("Template with name %s doesn't exists in the dir", filename)
  182. }