gview_parse.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. // Copyright GoFrame Author(https://github.com/gogf/gf). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package gview
  7. import (
  8. "bytes"
  9. "errors"
  10. "fmt"
  11. "github.com/gogf/gf/encoding/ghash"
  12. "github.com/gogf/gf/errors/gerror"
  13. "github.com/gogf/gf/internal/intlog"
  14. "github.com/gogf/gf/os/gfsnotify"
  15. "github.com/gogf/gf/os/gmlock"
  16. "github.com/gogf/gf/text/gstr"
  17. "github.com/gogf/gf/util/gconv"
  18. "github.com/gogf/gf/util/gutil"
  19. htmltpl "html/template"
  20. "strconv"
  21. "strings"
  22. texttpl "text/template"
  23. "github.com/gogf/gf/os/gres"
  24. "github.com/gogf/gf/container/gmap"
  25. "github.com/gogf/gf/os/gfile"
  26. "github.com/gogf/gf/os/glog"
  27. "github.com/gogf/gf/os/gspath"
  28. )
  29. const (
  30. // Template name for content parsing.
  31. templateNameForContentParsing = "TemplateContent"
  32. )
  33. // fileCacheItem is the cache item for template file.
  34. type fileCacheItem struct {
  35. path string
  36. folder string
  37. content string
  38. }
  39. var (
  40. // Templates cache map for template folder.
  41. // Note that there's no expiring logic for this map.
  42. templates = gmap.NewStrAnyMap(true)
  43. // Try-folders for resource template file searching.
  44. resourceTryFolders = []string{"template/", "template", "/template", "/template/"}
  45. )
  46. // Parse parses given template file <file> with given template variables <params>
  47. // and returns the parsed template content.
  48. func (view *View) Parse(file string, params ...Params) (result string, err error) {
  49. var tpl interface{}
  50. // It caches the file, folder and its content to enhance performance.
  51. r := view.fileCacheMap.GetOrSetFuncLock(file, func() interface{} {
  52. var (
  53. path string
  54. folder string
  55. content string
  56. resource *gres.File
  57. )
  58. // Searching the absolute file path for <file>.
  59. path, folder, resource, err = view.searchFile(file)
  60. if err != nil {
  61. return nil
  62. }
  63. if resource != nil {
  64. content = gconv.UnsafeBytesToStr(resource.Content())
  65. } else {
  66. content = gfile.GetContentsWithCache(path)
  67. }
  68. // Monitor template files changes using fsnotify asynchronously.
  69. if resource == nil {
  70. if _, err := gfsnotify.AddOnce("gview.Parse:"+folder, folder, func(event *gfsnotify.Event) {
  71. // CLEAR THEM ALL.
  72. view.fileCacheMap.Clear()
  73. templates.Clear()
  74. gfsnotify.Exit()
  75. }); err != nil {
  76. intlog.Error(err)
  77. }
  78. }
  79. return &fileCacheItem{
  80. path: path,
  81. folder: folder,
  82. content: content,
  83. }
  84. })
  85. if r == nil {
  86. return
  87. }
  88. item := r.(*fileCacheItem)
  89. // It's not necessary continuing parsing if template content is empty.
  90. if item.content == "" {
  91. return "", nil
  92. }
  93. // Get the template object instance for <folder>.
  94. tpl, err = view.getTemplate(item.path, item.folder, fmt.Sprintf(`*%s`, gfile.Ext(item.path)))
  95. if err != nil {
  96. return "", err
  97. }
  98. // Using memory lock to ensure concurrent safety for template parsing.
  99. gmlock.LockFunc("gview.Parse:"+item.path, func() {
  100. if view.config.AutoEncode {
  101. tpl, err = tpl.(*htmltpl.Template).Parse(item.content)
  102. } else {
  103. tpl, err = tpl.(*texttpl.Template).Parse(item.content)
  104. }
  105. if err != nil && item.path != "" {
  106. err = gerror.Wrap(err, item.path)
  107. }
  108. })
  109. if err != nil {
  110. return "", err
  111. }
  112. // Note that the template variable assignment cannot change the value
  113. // of the existing <params> or view.data because both variables are pointers.
  114. // It needs to merge the values of the two maps into a new map.
  115. variables := gutil.MapMergeCopy(params...)
  116. if len(view.data) > 0 {
  117. gutil.MapMerge(variables, view.data)
  118. }
  119. buffer := bytes.NewBuffer(nil)
  120. if view.config.AutoEncode {
  121. newTpl, err := tpl.(*htmltpl.Template).Clone()
  122. if err != nil {
  123. return "", err
  124. }
  125. if err := newTpl.Execute(buffer, variables); err != nil {
  126. return "", err
  127. }
  128. } else {
  129. if err := tpl.(*texttpl.Template).Execute(buffer, variables); err != nil {
  130. return "", err
  131. }
  132. }
  133. // TODO any graceful plan to replace "<no value>"?
  134. result = gstr.Replace(buffer.String(), "<no value>", "")
  135. result = view.i18nTranslate(result, variables)
  136. return result, nil
  137. }
  138. // ParseDefault parses the default template file with params.
  139. func (view *View) ParseDefault(params ...Params) (result string, err error) {
  140. return view.Parse(view.config.DefaultFile, params...)
  141. }
  142. // ParseContent parses given template content <content> with template variables <params>
  143. // and returns the parsed content in []byte.
  144. func (view *View) ParseContent(content string, params ...Params) (string, error) {
  145. // It's not necessary continuing parsing if template content is empty.
  146. if content == "" {
  147. return "", nil
  148. }
  149. err := (error)(nil)
  150. key := fmt.Sprintf("%s_%v_%v", templateNameForContentParsing, view.config.Delimiters, view.config.AutoEncode)
  151. tpl := templates.GetOrSetFuncLock(key, func() interface{} {
  152. if view.config.AutoEncode {
  153. return htmltpl.New(templateNameForContentParsing).Delims(
  154. view.config.Delimiters[0],
  155. view.config.Delimiters[1],
  156. ).Funcs(view.funcMap)
  157. }
  158. return texttpl.New(templateNameForContentParsing).Delims(
  159. view.config.Delimiters[0],
  160. view.config.Delimiters[1],
  161. ).Funcs(view.funcMap)
  162. })
  163. // Using memory lock to ensure concurrent safety for content parsing.
  164. hash := strconv.FormatUint(ghash.DJBHash64([]byte(content)), 10)
  165. gmlock.LockFunc("gview.ParseContent:"+hash, func() {
  166. if view.config.AutoEncode {
  167. tpl, err = tpl.(*htmltpl.Template).Parse(content)
  168. } else {
  169. tpl, err = tpl.(*texttpl.Template).Parse(content)
  170. }
  171. })
  172. if err != nil {
  173. return "", err
  174. }
  175. // Note that the template variable assignment cannot change the value
  176. // of the existing <params> or view.data because both variables are pointers.
  177. // It needs to merge the values of the two maps into a new map.
  178. variables := gutil.MapMergeCopy(params...)
  179. if len(view.data) > 0 {
  180. gutil.MapMerge(variables, view.data)
  181. }
  182. buffer := bytes.NewBuffer(nil)
  183. if view.config.AutoEncode {
  184. newTpl, err := tpl.(*htmltpl.Template).Clone()
  185. if err != nil {
  186. return "", err
  187. }
  188. if err := newTpl.Execute(buffer, variables); err != nil {
  189. return "", err
  190. }
  191. } else {
  192. if err := tpl.(*texttpl.Template).Execute(buffer, variables); err != nil {
  193. return "", err
  194. }
  195. }
  196. // TODO any graceful plan to replace "<no value>"?
  197. result := gstr.Replace(buffer.String(), "<no value>", "")
  198. result = view.i18nTranslate(result, variables)
  199. return result, nil
  200. }
  201. // getTemplate returns the template object associated with given template file <path>.
  202. // It uses template cache to enhance performance, that is, it will return the same template object
  203. // with the same given <path>. It will also automatically refresh the template cache
  204. // if the template files under <path> changes (recursively).
  205. func (view *View) getTemplate(filePath, folderPath, pattern string) (tpl interface{}, err error) {
  206. // Key for template cache.
  207. key := fmt.Sprintf("%s_%v", filePath, view.config.Delimiters)
  208. result := templates.GetOrSetFuncLock(key, func() interface{} {
  209. tplName := filePath
  210. if view.config.AutoEncode {
  211. tpl = htmltpl.New(tplName).Delims(
  212. view.config.Delimiters[0],
  213. view.config.Delimiters[1],
  214. ).Funcs(view.funcMap)
  215. } else {
  216. tpl = texttpl.New(tplName).Delims(
  217. view.config.Delimiters[0],
  218. view.config.Delimiters[1],
  219. ).Funcs(view.funcMap)
  220. }
  221. // Firstly checking the resource manager.
  222. if !gres.IsEmpty() {
  223. if files := gres.ScanDirFile(folderPath, pattern, true); len(files) > 0 {
  224. var err error
  225. if view.config.AutoEncode {
  226. t := tpl.(*htmltpl.Template)
  227. for _, v := range files {
  228. _, err = t.New(v.FileInfo().Name()).Parse(string(v.Content()))
  229. if err != nil {
  230. err = view.formatTemplateObjectCreatingError(v.Name(), tplName, err)
  231. return nil
  232. }
  233. }
  234. } else {
  235. t := tpl.(*texttpl.Template)
  236. for _, v := range files {
  237. _, err = t.New(v.FileInfo().Name()).Parse(string(v.Content()))
  238. if err != nil {
  239. err = view.formatTemplateObjectCreatingError(v.Name(), tplName, err)
  240. return nil
  241. }
  242. }
  243. }
  244. return tpl
  245. }
  246. }
  247. // Secondly checking the file system.
  248. var (
  249. files []string
  250. )
  251. files, err = gfile.ScanDir(folderPath, pattern, true)
  252. if err != nil {
  253. return nil
  254. }
  255. if view.config.AutoEncode {
  256. t := tpl.(*htmltpl.Template)
  257. for _, file := range files {
  258. if _, err = t.Parse(gfile.GetContents(file)); err != nil {
  259. err = view.formatTemplateObjectCreatingError(file, tplName, err)
  260. return nil
  261. }
  262. }
  263. } else {
  264. t := tpl.(*texttpl.Template)
  265. for _, file := range files {
  266. if _, err = t.Parse(gfile.GetContents(file)); err != nil {
  267. err = view.formatTemplateObjectCreatingError(file, tplName, err)
  268. return nil
  269. }
  270. }
  271. }
  272. return tpl
  273. })
  274. if result != nil {
  275. return result, nil
  276. }
  277. return
  278. }
  279. // formatTemplateObjectCreatingError formats the error that creted from creating template object.
  280. func (view *View) formatTemplateObjectCreatingError(filePath, tplName string, err error) error {
  281. if err != nil {
  282. return gerror.NewSkip(1, gstr.Replace(err.Error(), tplName, filePath))
  283. }
  284. return nil
  285. }
  286. // searchFile returns the found absolute path for <file> and its template folder path.
  287. // Note that, the returned <folder> is the template folder path, but not the folder of
  288. // the returned template file <path>.
  289. func (view *View) searchFile(file string) (path string, folder string, resource *gres.File, err error) {
  290. // Firstly checking the resource manager.
  291. if !gres.IsEmpty() {
  292. // Try folders.
  293. for _, folderPath := range resourceTryFolders {
  294. if resource = gres.Get(folderPath + file); resource != nil {
  295. path = resource.Name()
  296. folder = folderPath
  297. return
  298. }
  299. }
  300. // Search folders.
  301. view.paths.RLockFunc(func(array []string) {
  302. for _, v := range array {
  303. v = strings.TrimRight(v, "/"+gfile.Separator)
  304. if resource = gres.Get(v + "/" + file); resource != nil {
  305. path = resource.Name()
  306. folder = v
  307. break
  308. }
  309. if resource = gres.Get(v + "/template/" + file); resource != nil {
  310. path = resource.Name()
  311. folder = v + "/template"
  312. break
  313. }
  314. }
  315. })
  316. }
  317. // Secondly checking the file system.
  318. if path == "" {
  319. view.paths.RLockFunc(func(array []string) {
  320. for _, folderPath := range array {
  321. folderPath = strings.TrimRight(folderPath, gfile.Separator)
  322. if path, _ = gspath.Search(folderPath, file); path != "" {
  323. folder = folderPath
  324. break
  325. }
  326. if path, _ = gspath.Search(folderPath+gfile.Separator+"template", file); path != "" {
  327. folder = folderPath + gfile.Separator + "template"
  328. break
  329. }
  330. }
  331. })
  332. }
  333. // Error checking.
  334. if path == "" {
  335. buffer := bytes.NewBuffer(nil)
  336. if view.paths.Len() > 0 {
  337. buffer.WriteString(fmt.Sprintf("[gview] cannot find template file \"%s\" in following paths:", file))
  338. view.paths.RLockFunc(func(array []string) {
  339. index := 1
  340. for _, folderPath := range array {
  341. folderPath = strings.TrimRight(folderPath, "/")
  342. if folderPath == "" {
  343. folderPath = "/"
  344. }
  345. buffer.WriteString(fmt.Sprintf("\n%d. %s", index, folderPath))
  346. index++
  347. buffer.WriteString(fmt.Sprintf("\n%d. %s", index, strings.TrimRight(folderPath, "/")+gfile.Separator+"template"))
  348. index++
  349. }
  350. })
  351. } else {
  352. buffer.WriteString(fmt.Sprintf("[gview] cannot find template file \"%s\" with no path set/add", file))
  353. }
  354. if errorPrint() {
  355. glog.Error(buffer.String())
  356. }
  357. err = errors.New(fmt.Sprintf(`template file "%s" not found`, file))
  358. }
  359. return
  360. }