handlebars.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. package view
  2. import (
  3. "fmt"
  4. "io"
  5. "io/ioutil"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. "sync"
  10. "github.com/aymerick/raymond"
  11. )
  12. // HandlebarsEngine contains the handlebars view engine structure.
  13. type HandlebarsEngine struct {
  14. // files configuration
  15. directory string
  16. extension string
  17. assetFn func(name string) ([]byte, error) // for embedded, in combination with directory & extension
  18. namesFn func() []string // for embedded, in combination with directory & extension
  19. reload bool // if true, each time the ExecuteWriter is called the templates will be reloaded.
  20. // parser configuration
  21. layout string
  22. rmu sync.RWMutex // locks for helpers and `ExecuteWiter` when `reload` is true.
  23. helpers map[string]interface{}
  24. templateCache map[string]*raymond.Template
  25. }
  26. // Handlebars creates and returns a new handlebars view engine.
  27. func Handlebars(directory, extension string) *HandlebarsEngine {
  28. s := &HandlebarsEngine{
  29. directory: directory,
  30. extension: extension,
  31. templateCache: make(map[string]*raymond.Template, 0),
  32. helpers: make(map[string]interface{}, 0),
  33. }
  34. // register the render helper here
  35. raymond.RegisterHelper("render", func(partial string, binding interface{}) raymond.SafeString {
  36. contents, err := s.executeTemplateBuf(partial, binding)
  37. if err != nil {
  38. return raymond.SafeString("template with name: " + partial + " couldn't not be found.")
  39. }
  40. return raymond.SafeString(contents)
  41. })
  42. return s
  43. }
  44. // Ext returns the file extension which this view engine is responsible to render.
  45. func (s *HandlebarsEngine) Ext() string {
  46. return s.extension
  47. }
  48. // Binary optionally, use it when template files are distributed
  49. // inside the app executable (.go generated files).
  50. //
  51. // The assetFn and namesFn can come from the go-bindata library.
  52. func (s *HandlebarsEngine) Binary(assetFn func(name string) ([]byte, error), namesFn func() []string) *HandlebarsEngine {
  53. s.assetFn, s.namesFn = assetFn, namesFn
  54. return s
  55. }
  56. // Reload if setted to true the templates are reloading on each render,
  57. // use it when you're in development and you're boring of restarting
  58. // the whole app when you edit a template file.
  59. //
  60. // Note that if `true` is passed then only one `View -> ExecuteWriter` will be render each time,
  61. // no concurrent access across clients, use it only on development status.
  62. // It's good to be used side by side with the https://github.com/kataras/rizla reloader for go source files.
  63. func (s *HandlebarsEngine) Reload(developmentMode bool) *HandlebarsEngine {
  64. s.reload = developmentMode
  65. return s
  66. }
  67. // Layout sets the layout template file which should use
  68. // the {{ yield }} func to yield the main template file
  69. // and optionally {{partial/partial_r/render}} to render
  70. // other template files like headers and footers.
  71. func (s *HandlebarsEngine) Layout(layoutFile string) *HandlebarsEngine {
  72. s.layout = layoutFile
  73. return s
  74. }
  75. // AddFunc adds the function to the template's function map.
  76. // It is legal to overwrite elements of the default actions:
  77. // - url func(routeName string, args ...string) string
  78. // - urlpath func(routeName string, args ...string) string
  79. // - render func(fullPartialName string) (raymond.HTML, error).
  80. func (s *HandlebarsEngine) AddFunc(funcName string, funcBody interface{}) {
  81. s.rmu.Lock()
  82. s.helpers[funcName] = funcBody
  83. s.rmu.Unlock()
  84. }
  85. // Load parses the templates to the engine.
  86. // It's alos responsible to add the necessary global functions.
  87. //
  88. // Returns an error if something bad happens, user is responsible to catch it.
  89. func (s *HandlebarsEngine) Load() error {
  90. if s.assetFn != nil && s.namesFn != nil {
  91. // embedded
  92. return s.loadAssets()
  93. }
  94. // load from directory, make the dir absolute here too.
  95. dir, err := filepath.Abs(s.directory)
  96. if err != nil {
  97. return err
  98. }
  99. // change the directory field configuration, load happens after directory has been setted, so we will not have any problems here.
  100. s.directory = dir
  101. return s.loadDirectory()
  102. }
  103. // loadDirectory builds the handlebars templates from directory.
  104. func (s *HandlebarsEngine) loadDirectory() error {
  105. // register the global helpers on the first load
  106. if len(s.templateCache) == 0 && s.helpers != nil {
  107. raymond.RegisterHelpers(s.helpers)
  108. }
  109. dir, extension := s.directory, s.extension
  110. // the render works like {{ render "myfile.html" theContext.PartialContext}}
  111. // instead of the html/template engine which works like {{ render "myfile.html"}} and accepts the parent binding, with handlebars we can't do that because of lack of runtime helpers (dublicate error)
  112. var templateErr error
  113. filepath.Walk(dir, func(path string, info os.FileInfo, _ error) error {
  114. if info == nil || info.IsDir() {
  115. return nil
  116. }
  117. rel, err := filepath.Rel(dir, path)
  118. if err != nil {
  119. return err
  120. }
  121. ext := filepath.Ext(rel)
  122. if ext == extension {
  123. buf, err := ioutil.ReadFile(path)
  124. contents := string(buf)
  125. if err != nil {
  126. templateErr = err
  127. return err
  128. }
  129. name := filepath.ToSlash(rel)
  130. tmpl, err := raymond.Parse(contents)
  131. if err != nil {
  132. templateErr = err
  133. return err
  134. }
  135. s.templateCache[name] = tmpl
  136. }
  137. return nil
  138. })
  139. return templateErr
  140. }
  141. // loadAssets loads the templates by binary, embedded.
  142. func (s *HandlebarsEngine) loadAssets() error {
  143. // register the global helpers
  144. if len(s.templateCache) == 0 && s.helpers != nil {
  145. raymond.RegisterHelpers(s.helpers)
  146. }
  147. virtualDirectory, virtualExtension := s.directory, s.extension
  148. assetFn, namesFn := s.assetFn, s.namesFn
  149. if len(virtualDirectory) > 0 {
  150. if virtualDirectory[0] == '.' { // first check for .wrong
  151. virtualDirectory = virtualDirectory[1:]
  152. }
  153. if virtualDirectory[0] == '/' || virtualDirectory[0] == os.PathSeparator { // second check for /something, (or ./something if we had dot on 0 it will be removed
  154. virtualDirectory = virtualDirectory[1:]
  155. }
  156. }
  157. var templateErr error
  158. names := namesFn()
  159. for _, path := range names {
  160. if !strings.HasPrefix(path, virtualDirectory) {
  161. continue
  162. }
  163. ext := filepath.Ext(path)
  164. if ext == virtualExtension {
  165. rel, err := filepath.Rel(virtualDirectory, path)
  166. if err != nil {
  167. templateErr = err
  168. return err
  169. }
  170. buf, err := assetFn(path)
  171. if err != nil {
  172. templateErr = err
  173. return err
  174. }
  175. contents := string(buf)
  176. name := filepath.ToSlash(rel)
  177. tmpl, err := raymond.Parse(contents)
  178. if err != nil {
  179. templateErr = err
  180. return err
  181. }
  182. s.templateCache[name] = tmpl
  183. }
  184. }
  185. return templateErr
  186. }
  187. func (s *HandlebarsEngine) fromCache(relativeName string) *raymond.Template {
  188. tmpl, ok := s.templateCache[relativeName]
  189. if !ok {
  190. return nil
  191. }
  192. return tmpl
  193. }
  194. func (s *HandlebarsEngine) executeTemplateBuf(name string, binding interface{}) (string, error) {
  195. if tmpl := s.fromCache(name); tmpl != nil {
  196. return tmpl.Exec(binding)
  197. }
  198. return "", nil
  199. }
  200. // ExecuteWriter executes a template and writes its result to the w writer.
  201. func (s *HandlebarsEngine) ExecuteWriter(w io.Writer, filename string, layout string, bindingData interface{}) error {
  202. // re-parse the templates if reload is enabled.
  203. if s.reload {
  204. // locks to fix #872, it's the simplest solution and the most correct,
  205. // to execute writers with "wait list", one at a time.
  206. s.rmu.Lock()
  207. defer s.rmu.Unlock()
  208. if err := s.Load(); err != nil {
  209. return err
  210. }
  211. }
  212. isLayout := false
  213. layout = getLayout(layout, s.layout)
  214. renderFilename := filename
  215. if layout != "" {
  216. isLayout = true
  217. renderFilename = layout // the render becomes the layout, and the name is the partial.
  218. }
  219. if tmpl := s.fromCache(renderFilename); tmpl != nil {
  220. binding := bindingData
  221. if isLayout {
  222. var context map[string]interface{}
  223. if m, is := binding.(map[string]interface{}); is { //handlebars accepts maps,
  224. context = m
  225. } else {
  226. return fmt.Errorf("Please provide a map[string]interface{} type as the binding instead of the %#v", binding)
  227. }
  228. contents, err := s.executeTemplateBuf(filename, binding)
  229. if err != nil {
  230. return err
  231. }
  232. if context == nil {
  233. context = make(map[string]interface{}, 1)
  234. }
  235. // I'm implemented the {{ yield }} as with the rest of template engines, so this is not inneed for iris, but the user can do that manually if want
  236. // there is no performanrce different: raymond.RegisterPartialTemplate(name, tmpl)
  237. context["yield"] = raymond.SafeString(contents)
  238. }
  239. res, err := tmpl.Exec(binding)
  240. if err != nil {
  241. return err
  242. }
  243. _, err = fmt.Fprint(w, res)
  244. return err
  245. }
  246. return fmt.Errorf("template with name %s[original name = %s] doesn't exists in the dir", renderFilename, filename)
  247. }