html.go 13 KB

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