handlebars.go 8.6 KB

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