html.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. package view
  2. import (
  3. "bytes"
  4. "fmt"
  5. "html/template"
  6. "io"
  7. "io/fs"
  8. "os"
  9. "path/filepath"
  10. "strings"
  11. "sync"
  12. "github.com/kataras/iris/v12/context"
  13. )
  14. // HTMLEngine contains the html view engine structure.
  15. type HTMLEngine struct {
  16. name string // the view engine's name, can be HTML, Ace or Pug.
  17. // the file system to load from.
  18. fs fs.FS
  19. // files configuration
  20. rootDir string
  21. extension string
  22. // if true, each time the ExecuteWriter is called the templates will be reloaded,
  23. // each ExecuteWriter waits to be finished before writing to a new one.
  24. reload bool
  25. // parser configuration
  26. options []string // (text) template options
  27. left string
  28. right string
  29. layout string
  30. rmu sync.RWMutex // locks for layoutFuncs and funcs
  31. layoutFuncs template.FuncMap
  32. funcs template.FuncMap
  33. //
  34. middleware func(name string, contents []byte) (string, error)
  35. onLoad func()
  36. onLoaded func()
  37. Templates *template.Template
  38. customCache []customTmp // required to load them again if reload is true.
  39. bufPool *sync.Pool
  40. //
  41. }
  42. type customTmp struct {
  43. name string
  44. contents []byte
  45. funcs template.FuncMap
  46. }
  47. var (
  48. _ Engine = (*HTMLEngine)(nil)
  49. _ EngineFuncer = (*HTMLEngine)(nil)
  50. )
  51. // HTML creates and returns a new html view engine.
  52. // The html engine used like the "html/template" standard go package
  53. // but with a lot of extra features.
  54. // The given "extension" MUST begin with a dot.
  55. //
  56. // Usage:
  57. // HTML("./views", ".html") or
  58. // HTML(iris.Dir("./views"), ".html") or
  59. // HTML(embed.FS, ".html") or HTML(AssetFile(), ".html") for embedded data or
  60. // HTML("","").ParseTemplate("hello", `[]byte("hello {{.Name}}")`, nil) for custom template parsing only.
  61. func HTML(dirOrFS interface{}, extension string) *HTMLEngine {
  62. s := &HTMLEngine{
  63. name: "HTML",
  64. fs: getFS(dirOrFS),
  65. rootDir: "/",
  66. extension: extension,
  67. reload: false,
  68. left: "{{",
  69. right: "}}",
  70. layout: "",
  71. layoutFuncs: template.FuncMap{
  72. "yield": func(binding interface{}) template.HTML {
  73. return template.HTML("")
  74. },
  75. },
  76. funcs: make(template.FuncMap),
  77. bufPool: &sync.Pool{New: func() interface{} {
  78. return new(bytes.Buffer)
  79. }},
  80. }
  81. return s
  82. }
  83. // RootDir sets the directory to be used as a starting point
  84. // to load templates from the provided file system.
  85. func (s *HTMLEngine) RootDir(root string) *HTMLEngine {
  86. if s.fs != nil && root != "" && root != "/" && root != "." && root != s.rootDir {
  87. sub, err := fs.Sub(s.fs, root)
  88. if err != nil {
  89. panic(err)
  90. }
  91. s.fs = sub // here so the "middleware" can work.
  92. }
  93. s.rootDir = filepath.ToSlash(root)
  94. return s
  95. }
  96. // Name returns the engine's name.
  97. func (s *HTMLEngine) Name() string {
  98. return s.name
  99. }
  100. // Ext returns the file extension which this view engine is responsible to render.
  101. // If the filename extension on ExecuteWriter is empty then this is appended.
  102. func (s *HTMLEngine) Ext() string {
  103. return s.extension
  104. }
  105. // Reload if set to true the templates are reloading on each render,
  106. // use it when you're in development and you're boring of restarting
  107. // the whole app when you edit a template file.
  108. //
  109. // Note that if `true` is passed then only one `View -> ExecuteWriter` will be render each time,
  110. // no concurrent access across clients, use it only on development status.
  111. // It's good to be used side by side with the https://github.com/kataras/rizla reloader for go source files.
  112. func (s *HTMLEngine) Reload(developmentMode bool) *HTMLEngine {
  113. s.reload = developmentMode
  114. return s
  115. }
  116. // Option sets options for the template. Options are described by
  117. // strings, either a simple string or "key=value". There can be at
  118. // most one equals sign in an option string. If the option string
  119. // is unrecognized or otherwise invalid, Option panics.
  120. //
  121. // Known options:
  122. //
  123. // missingkey: Control the behavior during execution if a map is
  124. // indexed with a key that is not present in the map.
  125. //
  126. // "missingkey=default" or "missingkey=invalid"
  127. // The default behavior: Do nothing and continue execution.
  128. // If printed, the result of the index operation is the string
  129. // "<no value>".
  130. // "missingkey=zero"
  131. // The operation returns the zero value for the map type's element.
  132. // "missingkey=error"
  133. // Execution stops immediately with an error.
  134. func (s *HTMLEngine) Option(opt ...string) *HTMLEngine {
  135. s.rmu.Lock()
  136. s.options = append(s.options, opt...)
  137. s.rmu.Unlock()
  138. return s
  139. }
  140. // Delims sets the action delimiters to the specified strings, to be used in
  141. // templates. An empty delimiter stands for the
  142. // corresponding default: {{ or }}.
  143. func (s *HTMLEngine) Delims(left, right string) *HTMLEngine {
  144. s.left, s.right = left, right
  145. return s
  146. }
  147. // Layout sets the layout template file which inside should use
  148. // the {{ yield . }} func to yield the main template file
  149. // and optionally {{partial/partial_r/render . }} to render other template files like headers and footers
  150. //
  151. // The 'tmplLayoutFile' is a relative path of the templates base directory,
  152. // for the template file with its extension.
  153. //
  154. // Example: HTML("./templates", ".html").Layout("layouts/mainLayout.html")
  155. //
  156. // // mainLayout.html is inside: "./templates/layouts/".
  157. //
  158. // Note: Layout can be changed for a specific call
  159. // action with the option: "layout" on the iris' context.Render function.
  160. func (s *HTMLEngine) Layout(layoutFile string) *HTMLEngine {
  161. s.layout = layoutFile
  162. return s
  163. }
  164. // AddLayoutFunc adds the function to the template's layout-only function map.
  165. // It is legal to overwrite elements of the default layout actions:
  166. // - yield func() (template.HTML, error)
  167. // - current func() (string, error)
  168. // - partial func(partialName string) (template.HTML, error)
  169. // - partial_r func(partialName string) (template.HTML, error)
  170. // - render func(fullPartialName string) (template.HTML, error).
  171. func (s *HTMLEngine) AddLayoutFunc(funcName string, funcBody interface{}) *HTMLEngine {
  172. s.rmu.Lock()
  173. s.layoutFuncs[funcName] = funcBody
  174. s.rmu.Unlock()
  175. return s
  176. }
  177. // AddFunc adds the function to the template's function map.
  178. // It is legal to overwrite elements of the default actions:
  179. // - url func(routeName string, args ...string) string
  180. // - urlpath func(routeName string, args ...string) string
  181. // - render func(fullPartialName string) (template.HTML, error).
  182. // - tr func(lang, key string, args ...interface{}) string
  183. func (s *HTMLEngine) AddFunc(funcName string, funcBody interface{}) {
  184. s.rmu.Lock()
  185. s.funcs[funcName] = funcBody
  186. s.rmu.Unlock()
  187. }
  188. // SetFuncs overrides the template funcs with the given "funcMap".
  189. func (s *HTMLEngine) SetFuncs(funcMap template.FuncMap) *HTMLEngine {
  190. s.rmu.Lock()
  191. s.funcs = funcMap
  192. s.rmu.Unlock()
  193. return s
  194. }
  195. // Funcs adds the elements of the argument map to the template's function map.
  196. // It is legal to overwrite elements of the map. The return
  197. // value is the template, so calls can be chained.
  198. func (s *HTMLEngine) Funcs(funcMap template.FuncMap) *HTMLEngine {
  199. s.rmu.Lock()
  200. for k, v := range funcMap {
  201. s.funcs[k] = v
  202. }
  203. s.rmu.Unlock()
  204. return s
  205. }
  206. // Load parses the templates to the engine.
  207. // It's also responsible to add the necessary global functions.
  208. //
  209. // Returns an error if something bad happens, caller is responsible to handle that.
  210. func (s *HTMLEngine) Load() error {
  211. s.rmu.Lock()
  212. defer s.rmu.Unlock()
  213. return s.load()
  214. }
  215. func (s *HTMLEngine) load() error {
  216. if s.onLoad != nil {
  217. s.onLoad()
  218. }
  219. if err := s.reloadCustomTemplates(); err != nil {
  220. return err
  221. }
  222. // If only custom templates should be loaded.
  223. if (s.fs == nil || context.IsNoOpFS(s.fs)) && len(s.Templates.DefinedTemplates()) > 0 {
  224. return nil
  225. }
  226. rootDirName := getRootDirName(s.fs)
  227. err := walk(s.fs, "", func(path string, info os.FileInfo, err error) error {
  228. if err != nil {
  229. return err
  230. }
  231. if info == nil || info.IsDir() {
  232. return nil
  233. }
  234. if s.extension != "" {
  235. if !strings.HasSuffix(path, s.extension) {
  236. return nil
  237. }
  238. }
  239. if s.rootDir == rootDirName {
  240. path = strings.TrimPrefix(path, rootDirName)
  241. path = strings.TrimPrefix(path, "/")
  242. }
  243. buf, err := asset(s.fs, path)
  244. if err != nil {
  245. return fmt.Errorf("%s: %w", path, err)
  246. }
  247. return s.parseTemplate(path, buf, nil)
  248. })
  249. if s.onLoaded != nil {
  250. s.onLoaded()
  251. }
  252. if err != nil {
  253. return err
  254. }
  255. if s.Templates == nil {
  256. return fmt.Errorf("no templates found")
  257. }
  258. return nil
  259. }
  260. func (s *HTMLEngine) reloadCustomTemplates() error {
  261. for _, tmpl := range s.customCache {
  262. if err := s.parseTemplate(tmpl.name, tmpl.contents, tmpl.funcs); err != nil {
  263. return err
  264. }
  265. }
  266. return nil
  267. }
  268. // ParseTemplate adds a custom template to the root template.
  269. func (s *HTMLEngine) ParseTemplate(name string, contents []byte, funcs template.FuncMap) (err error) {
  270. s.rmu.Lock()
  271. defer s.rmu.Unlock()
  272. s.customCache = append(s.customCache, customTmp{
  273. name: name,
  274. contents: contents,
  275. funcs: funcs,
  276. })
  277. return s.parseTemplate(name, contents, funcs)
  278. }
  279. func (s *HTMLEngine) parseTemplate(name string, contents []byte, funcs template.FuncMap) (err error) {
  280. s.initRootTmpl()
  281. name = strings.TrimPrefix(name, "/")
  282. tmpl := s.Templates.New(name)
  283. // tmpl.Option("missingkey=error")
  284. tmpl.Option(s.options...)
  285. var text string
  286. if s.middleware != nil {
  287. text, err = s.middleware(name, contents)
  288. if err != nil {
  289. return
  290. }
  291. } else {
  292. text = string(contents)
  293. }
  294. tmpl.Funcs(s.getBuiltinFuncs(name)).Funcs(s.funcs)
  295. if strings.Contains(name, "layout") {
  296. tmpl.Funcs(s.layoutFuncs)
  297. }
  298. if len(funcs) > 0 {
  299. tmpl.Funcs(funcs) // custom for this template.
  300. }
  301. _, err = tmpl.Parse(text)
  302. return
  303. }
  304. func (s *HTMLEngine) initRootTmpl() { // protected by the caller.
  305. if s.Templates == nil {
  306. // the root template should be the same,
  307. // no matter how many reloads as the
  308. // following unexported fields cannot be modified.
  309. // However, on reload they should be cleared otherwise we get an error.
  310. s.Templates = template.New(s.rootDir)
  311. s.Templates.Delims(s.left, s.right)
  312. }
  313. }
  314. func (s *HTMLEngine) executeTemplateBuf(name string, binding interface{}) (string, error) {
  315. buf := s.bufPool.Get().(*bytes.Buffer)
  316. buf.Reset()
  317. err := s.Templates.ExecuteTemplate(buf, name, binding)
  318. result := buf.String()
  319. s.bufPool.Put(buf)
  320. return result, err
  321. }
  322. func (s *HTMLEngine) getBuiltinRuntimeLayoutFuncs(name string) template.FuncMap {
  323. funcs := template.FuncMap{
  324. "yield": func(binding interface{}) (template.HTML, error) {
  325. result, err := s.executeTemplateBuf(name, binding)
  326. // Return safe HTML here since we are rendering our own template.
  327. return template.HTML(result), err
  328. },
  329. }
  330. return funcs
  331. }
  332. func (s *HTMLEngine) getBuiltinFuncs(name string) template.FuncMap {
  333. funcs := template.FuncMap{
  334. "part": func(partName string, binding interface{}) (template.HTML, error) {
  335. nameTemp := strings.ReplaceAll(name, s.extension, "")
  336. fullPartName := fmt.Sprintf("%s-%s", nameTemp, partName)
  337. result, err := s.executeTemplateBuf(fullPartName, binding)
  338. if err != nil {
  339. return "", nil
  340. }
  341. return template.HTML(result), err
  342. },
  343. "current": func() (string, error) {
  344. return name, nil
  345. },
  346. "partial": func(partialName string, binding interface{}) (template.HTML, error) {
  347. fullPartialName := fmt.Sprintf("%s-%s", partialName, name)
  348. if s.Templates.Lookup(fullPartialName) != nil {
  349. result, err := s.executeTemplateBuf(fullPartialName, binding)
  350. return template.HTML(result), err
  351. }
  352. return "", nil
  353. },
  354. // partial related to current page,
  355. // it would be easier for adding pages' style/script inline
  356. // for example when using partial_r '.script' in layout.html
  357. // templates/users/index.html would load templates/users/index.script.html
  358. "partial_r": func(partialName string, binding interface{}) (template.HTML, error) {
  359. ext := filepath.Ext(name)
  360. root := name[:len(name)-len(ext)]
  361. fullPartialName := fmt.Sprintf("%s%s%s", root, partialName, ext)
  362. if s.Templates.Lookup(fullPartialName) != nil {
  363. result, err := s.executeTemplateBuf(fullPartialName, binding)
  364. return template.HTML(result), err
  365. }
  366. return "", nil
  367. },
  368. "render": func(fullPartialName string, binding interface{}) (template.HTML, error) {
  369. result, err := s.executeTemplateBuf(fullPartialName, binding)
  370. return template.HTML(result), err
  371. },
  372. }
  373. return funcs
  374. }
  375. // ExecuteWriter executes a template and writes its result to the w writer.
  376. func (s *HTMLEngine) ExecuteWriter(w io.Writer, name string, layout string, bindingData interface{}) error {
  377. // re-parse the templates if reload is enabled.
  378. if s.reload {
  379. s.rmu.Lock()
  380. defer s.rmu.Unlock()
  381. s.Templates = nil
  382. // we lose the templates parsed manually, so store them when it's called
  383. // in order for load to take care of them too.
  384. if err := s.load(); err != nil {
  385. return err
  386. }
  387. }
  388. if layout = getLayout(layout, s.layout); layout != "" {
  389. lt := s.Templates.Lookup(layout)
  390. if lt == nil {
  391. return ErrNotExist{Name: layout, IsLayout: true, Data: bindingData}
  392. }
  393. return lt.Funcs(s.getBuiltinRuntimeLayoutFuncs(name)).Execute(w, bindingData)
  394. }
  395. t := s.Templates.Lookup(name)
  396. if t == nil {
  397. return ErrNotExist{Name: name, IsLayout: false, Data: bindingData}
  398. }
  399. return t.Execute(w, bindingData)
  400. }