html.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. package view
  2. import (
  3. "bytes"
  4. "fmt"
  5. "html/template"
  6. "io"
  7. "io/ioutil"
  8. "os"
  9. "path/filepath"
  10. "strings"
  11. "sync"
  12. "time"
  13. )
  14. type (
  15. // HTMLEngine contains the html view engine structure.
  16. HTMLEngine struct {
  17. // files configuration
  18. directory string
  19. extension string
  20. assetFn func(name string) ([]byte, error) // for embedded, in combination with directory & extension
  21. namesFn func() []string // for embedded, in combination with directory & extension
  22. reload bool // if true, each time the ExecuteWriter is called the templates will be reloaded, each ExecuteWriter waits to be finished before writing to a new one.
  23. // parser configuration
  24. options []string // text options
  25. left string
  26. right string
  27. layout string
  28. rmu sync.RWMutex // locks for layoutFuncs and funcs
  29. layoutFuncs map[string]interface{}
  30. funcs map[string]interface{}
  31. //
  32. middleware func(name string, contents string) (string, error)
  33. Templates *template.Template
  34. //
  35. }
  36. )
  37. var _ Engine = &HTMLEngine{}
  38. var emptyFuncs = template.FuncMap{
  39. "yield": func() (string, error) {
  40. return "", fmt.Errorf("yield was called, yet no layout defined")
  41. },
  42. "partial": func() (string, error) {
  43. return "", fmt.Errorf("block was called, yet no layout defined")
  44. },
  45. "partial_r": func() (string, error) {
  46. return "", fmt.Errorf("block was called, yet no layout defined")
  47. },
  48. "current": func() (string, error) {
  49. return "", nil
  50. }, "render": func() (string, error) {
  51. return "", nil
  52. },
  53. }
  54. // HTML creates and returns a new html view engine.
  55. // The html engine used like the "html/template" standard go package
  56. // but with a lot of extra features.
  57. func HTML(directory, extension string) *HTMLEngine {
  58. s := &HTMLEngine{
  59. directory: directory,
  60. extension: extension,
  61. assetFn: nil,
  62. namesFn: nil,
  63. reload: false,
  64. left: "{{",
  65. right: "}}",
  66. layout: "",
  67. layoutFuncs: make(map[string]interface{}, 0),
  68. funcs: make(map[string]interface{}, 0),
  69. }
  70. return s
  71. }
  72. // Ext returns the file extension which this view engine is responsible to render.
  73. func (s *HTMLEngine) Ext() string {
  74. return s.extension
  75. }
  76. // Binary optionally, use it when template files are distributed
  77. // inside the app executable (.go generated files).
  78. //
  79. // The assetFn and namesFn can come from the go-bindata library.
  80. func (s *HTMLEngine) Binary(assetFn func(name string) ([]byte, error), namesFn func() []string) *HTMLEngine {
  81. s.assetFn, s.namesFn = assetFn, namesFn
  82. return s
  83. }
  84. // Reload if setted to true the templates are reloading on each render,
  85. // use it when you're in development and you're boring of restarting
  86. // the whole app when you edit a template file.
  87. //
  88. // Note that if `true` is passed then only one `View -> ExecuteWriter` will be render each time,
  89. // no concurrent access across clients, use it only on development status.
  90. // It's good to be used side by side with the https://github.com/kataras/rizla reloader for go source files.
  91. func (s *HTMLEngine) Reload(developmentMode bool) *HTMLEngine {
  92. s.reload = developmentMode
  93. return s
  94. }
  95. // Option sets options for the template. Options are described by
  96. // strings, either a simple string or "key=value". There can be at
  97. // most one equals sign in an option string. If the option string
  98. // is unrecognized or otherwise invalid, Option panics.
  99. //
  100. // Known options:
  101. //
  102. // missingkey: Control the behavior during execution if a map is
  103. // indexed with a key that is not present in the map.
  104. // "missingkey=default" or "missingkey=invalid"
  105. // The default behavior: Do nothing and continue execution.
  106. // If printed, the result of the index operation is the string
  107. // "<no value>".
  108. // "missingkey=zero"
  109. // The operation returns the zero value for the map type's element.
  110. // "missingkey=error"
  111. // Execution stops immediately with an error.
  112. //
  113. func (s *HTMLEngine) Option(opt ...string) *HTMLEngine {
  114. s.rmu.Lock()
  115. s.options = append(s.options, opt...)
  116. s.rmu.Unlock()
  117. return s
  118. }
  119. // Delims sets the action delimiters to the specified strings, to be used in
  120. // subsequent calls to Parse, ParseFiles, or ParseGlob. Nested template
  121. // definitions will inherit the settings. An empty delimiter stands for the
  122. // corresponding default: {{ or }}.
  123. func (s *HTMLEngine) Delims(left, right string) *HTMLEngine {
  124. s.left, s.right = left, right
  125. return s
  126. }
  127. // Layout sets the layout template file which inside should use
  128. // the {{ yield }} func to yield the main template file
  129. // and optionally {{partial/partial_r/render}} to render other template files like headers and footers
  130. //
  131. // The 'tmplLayoutFile' is a relative path of the templates base directory,
  132. // for the template file with its extension.
  133. //
  134. // Example: HTML("./templates", ".html").Layout("layouts/mainLayout.html")
  135. // // mainLayout.html is inside: "./templates/layouts/".
  136. //
  137. // Note: Layout can be changed for a specific call
  138. // action with the option: "layout" on the iris' context.Render function.
  139. func (s *HTMLEngine) Layout(layoutFile string) *HTMLEngine {
  140. s.layout = layoutFile
  141. return s
  142. }
  143. // AddLayoutFunc adds the function to the template's layout-only function map.
  144. // It is legal to overwrite elements of the default layout actions:
  145. // - yield func() (template.HTML, error)
  146. // - current func() (string, error)
  147. // - partial func(partialName string) (template.HTML, error)
  148. // - partial_r func(partialName string) (template.HTML, error)
  149. // - render func(fullPartialName string) (template.HTML, error).
  150. func (s *HTMLEngine) AddLayoutFunc(funcName string, funcBody interface{}) *HTMLEngine {
  151. s.rmu.Lock()
  152. s.layoutFuncs[funcName] = funcBody
  153. s.rmu.Unlock()
  154. return s
  155. }
  156. // AddFunc adds the function to the template's function map.
  157. // It is legal to overwrite elements of the default actions:
  158. // - url func(routeName string, args ...string) string
  159. // - urlpath func(routeName string, args ...string) string
  160. // - render func(fullPartialName string) (template.HTML, error).
  161. func (s *HTMLEngine) AddFunc(funcName string, funcBody interface{}) {
  162. s.rmu.Lock()
  163. s.funcs[funcName] = funcBody
  164. s.rmu.Unlock()
  165. }
  166. // Load parses the templates to the engine.
  167. // It's also responsible to add the necessary global functions.
  168. //
  169. // Returns an error if something bad happens, user is responsible to catch it.
  170. func (s *HTMLEngine) Load() error {
  171. // No need to make this with a complicated and "pro" way, just add lockers to the `ExecuteWriter`.
  172. // if `Reload(true)` and add a note for non conc access on dev mode.
  173. // atomic.StoreUint32(&s.isLoading, 1)
  174. // s.rmu.Lock()
  175. // defer func() {
  176. // s.rmu.Unlock()
  177. // atomic.StoreUint32(&s.isLoading, 0)
  178. // }()
  179. if s.assetFn != nil && s.namesFn != nil {
  180. // NOT NECESSARY "fix" of https://github.com/kataras/iris/issues/784,
  181. // IT'S BAD CODE WRITTEN WE KEEP HERE ONLY FOR A REMINDER
  182. // for any future questions.
  183. //
  184. // if strings.HasPrefix(s.directory, "../") {
  185. // // this and some more additions are fixes for https://github.com/kataras/iris/issues/784
  186. // // however, the dev SHOULD
  187. // // run the go-bindata command from the "$dir" parent directory
  188. // // and just use the ./$dir in the declaration,
  189. // // so all these fixes are not really necessary but they are here
  190. // // for the future
  191. // dir, err := filepath.Abs(s.directory)
  192. // // the absolute dir here can be invalid if running from other
  193. // // folder but we really don't care
  194. // // when we're working with the bindata because
  195. // // we only care for its relative directory
  196. // // see `loadAssets` for more.
  197. // if err != nil {
  198. // return err
  199. // }
  200. // s.directory = dir
  201. // }
  202. // embedded
  203. return s.loadAssets()
  204. }
  205. // load from directory, make the dir absolute here too.
  206. dir, err := filepath.Abs(s.directory)
  207. if err != nil {
  208. return err
  209. }
  210. // change the directory field configuration, load happens after directory has been setted, so we will not have any problems here.
  211. s.directory = dir
  212. return s.loadDirectory()
  213. }
  214. // loadDirectory builds the templates from directory.
  215. func (s *HTMLEngine) loadDirectory() error {
  216. dir, extension := s.directory, s.extension
  217. var templateErr error
  218. s.Templates = template.New(dir)
  219. s.Templates.Delims(s.left, s.right)
  220. filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
  221. if info == nil || info.IsDir() {
  222. } else {
  223. rel, err := filepath.Rel(dir, path)
  224. if err != nil {
  225. templateErr = err
  226. return err
  227. }
  228. ext := filepath.Ext(path)
  229. if ext == extension {
  230. buf, err := ioutil.ReadFile(path)
  231. if err != nil {
  232. templateErr = err
  233. return err
  234. }
  235. contents := string(buf)
  236. name := filepath.ToSlash(rel)
  237. tmpl := s.Templates.New(name)
  238. tmpl.Option(s.options...)
  239. if s.middleware != nil {
  240. contents, err = s.middleware(name, contents)
  241. }
  242. if err != nil {
  243. templateErr = err
  244. return err
  245. }
  246. //s.mu.Lock()
  247. // Add our funcmaps.
  248. _, err = tmpl.Funcs(emptyFuncs).Funcs(s.funcs).Parse(contents)
  249. //s.mu.Unlock()
  250. if err != nil {
  251. templateErr = err
  252. return err
  253. }
  254. }
  255. }
  256. return nil
  257. })
  258. return templateErr
  259. }
  260. // loadAssets loads the templates by binary (go-bindata for embedded).
  261. func (s *HTMLEngine) loadAssets() error {
  262. virtualDirectory, virtualExtension := s.directory, s.extension
  263. assetFn, namesFn := s.assetFn, s.namesFn
  264. var templateErr error
  265. s.Templates = template.New(virtualDirectory)
  266. s.Templates.Delims(s.left, s.right)
  267. names := namesFn()
  268. if len(virtualDirectory) > 0 {
  269. if virtualDirectory[0] == '.' { // first check for .wrong
  270. virtualDirectory = virtualDirectory[1:]
  271. }
  272. if virtualDirectory[0] == '/' || virtualDirectory[0] == os.PathSeparator { // second check for /something, (or ./something if we had dot on 0 it will be removed
  273. virtualDirectory = virtualDirectory[1:]
  274. }
  275. }
  276. for _, path := range names {
  277. // if filepath.IsAbs(virtualDirectory) {
  278. // // fixes https://github.com/kataras/iris/issues/784
  279. // // we take the absolute fullpath of the template file.
  280. // pathFileAbs, err := filepath.Abs(path)
  281. // if err != nil {
  282. // templateErr = err
  283. // continue
  284. // }
  285. //
  286. // path = pathFileAbs
  287. // }
  288. // bindata may contain more files than the templates
  289. // so keep that check as it's.
  290. if !strings.HasPrefix(path, virtualDirectory) {
  291. continue
  292. }
  293. ext := filepath.Ext(path)
  294. // check if extension matches
  295. if ext == virtualExtension {
  296. // take the relative path of the path as base of
  297. // virtualDirectory (the absolute path of the view engine that dev passed).
  298. rel, err := filepath.Rel(virtualDirectory, path)
  299. if err != nil {
  300. templateErr = err
  301. continue
  302. }
  303. // // take the current working directory
  304. // cpath, err := filepath.Abs(".")
  305. // if err == nil {
  306. // // set the path as relative to "path" of the current working dir.
  307. // // fixes https://github.com/kataras/iris/issues/784
  308. // rpath, err := filepath.Rel(cpath, path)
  309. // // fix view: Asset not found for path ''
  310. // if err == nil && rpath != "" {
  311. // path = rpath
  312. // }
  313. // }
  314. buf, err := assetFn(path)
  315. if err != nil {
  316. templateErr = fmt.Errorf("%v for path '%s'", err, path)
  317. continue
  318. }
  319. contents := string(buf)
  320. name := filepath.ToSlash(rel)
  321. // name should be the filename of the template.
  322. tmpl := s.Templates.New(name)
  323. tmpl.Option(s.options...)
  324. if s.middleware != nil {
  325. contents, err = s.middleware(name, contents)
  326. if err != nil {
  327. templateErr = fmt.Errorf("%v for name '%s'", err, name)
  328. continue
  329. }
  330. }
  331. // Add our funcmaps.
  332. tmpl.Funcs(emptyFuncs).Funcs(s.funcs).Parse(contents)
  333. }
  334. }
  335. return templateErr
  336. }
  337. func (s *HTMLEngine) executeTemplateBuf(name string, binding interface{}) (*bytes.Buffer, error) {
  338. buf := new(bytes.Buffer)
  339. err := s.Templates.ExecuteTemplate(buf, name, binding)
  340. return buf, err
  341. }
  342. func (s *HTMLEngine) layoutFuncsFor(name string, binding interface{}) {
  343. funcs := template.FuncMap{
  344. "yield": func() (template.HTML, error) {
  345. buf, err := s.executeTemplateBuf(name, binding)
  346. // Return safe HTML here since we are rendering our own template.
  347. return template.HTML(buf.String()), err
  348. },
  349. "current": func() (string, error) {
  350. return name, nil
  351. },
  352. "partial": func(partialName string) (template.HTML, error) {
  353. fullPartialName := fmt.Sprintf("%s-%s", partialName, name)
  354. if s.Templates.Lookup(fullPartialName) != nil {
  355. buf, err := s.executeTemplateBuf(fullPartialName, binding)
  356. return template.HTML(buf.String()), err
  357. }
  358. return "", nil
  359. },
  360. //partial related to current page,
  361. //it would be easier for adding pages' style/script inline
  362. //for example when using partial_r '.script' in layout.html
  363. //templates/users/index.html would load templates/users/index.script.html
  364. "partial_r": func(partialName string) (template.HTML, error) {
  365. ext := filepath.Ext(name)
  366. root := name[:len(name)-len(ext)]
  367. fullPartialName := fmt.Sprintf("%s%s%s", root, partialName, ext)
  368. if s.Templates.Lookup(fullPartialName) != nil {
  369. buf, err := s.executeTemplateBuf(fullPartialName, binding)
  370. return template.HTML(buf.String()), err
  371. }
  372. return "", nil
  373. },
  374. "render": func(fullPartialName string) (template.HTML, error) {
  375. buf, err := s.executeTemplateBuf(fullPartialName, binding)
  376. return template.HTML(buf.String()), err
  377. },
  378. }
  379. for k, v := range s.layoutFuncs {
  380. funcs[k] = v
  381. }
  382. if tpl := s.Templates.Lookup(name); tpl != nil {
  383. tpl.Funcs(funcs)
  384. }
  385. }
  386. func (s *HTMLEngine) runtimeFuncsFor(name string, binding interface{}) {
  387. funcs := template.FuncMap{
  388. "render": func(fullPartialName string) (template.HTML, error) {
  389. buf, err := s.executeTemplateBuf(fullPartialName, binding)
  390. return template.HTML(buf.String()), err
  391. },
  392. }
  393. if tpl := s.Templates.Lookup(name); tpl != nil {
  394. tpl.Funcs(funcs)
  395. }
  396. }
  397. var zero = time.Time{}
  398. // ExecuteWriter executes a template and writes its result to the w writer.
  399. func (s *HTMLEngine) ExecuteWriter(w io.Writer, name string, layout string, bindingData interface{}) error {
  400. // re-parse the templates if reload is enabled.
  401. if s.reload {
  402. // locks to fix #872, it's the simplest solution and the most correct,
  403. // to execute writers with "wait list", one at a time.
  404. s.rmu.Lock()
  405. defer s.rmu.Unlock()
  406. if err := s.Load(); err != nil {
  407. return err
  408. }
  409. }
  410. layout = getLayout(layout, s.layout)
  411. if layout != "" {
  412. s.layoutFuncsFor(name, bindingData)
  413. name = layout
  414. } else {
  415. s.runtimeFuncsFor(name, bindingData)
  416. }
  417. return s.Templates.ExecuteTemplate(w, name, bindingData)
  418. }