html.go 16 KB

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