template.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. // Copyright 2014 beego Author. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package beego
  15. import (
  16. "errors"
  17. "fmt"
  18. "html/template"
  19. "io"
  20. "io/ioutil"
  21. "net/http"
  22. "os"
  23. "path/filepath"
  24. "regexp"
  25. "strings"
  26. "sync"
  27. "github.com/astaxie/beego/logs"
  28. "github.com/astaxie/beego/utils"
  29. )
  30. var (
  31. beegoTplFuncMap = make(template.FuncMap)
  32. beeViewPathTemplateLocked = false
  33. // beeViewPathTemplates caching map and supported template file extensions per view
  34. beeViewPathTemplates = make(map[string]map[string]*template.Template)
  35. templatesLock sync.RWMutex
  36. // beeTemplateExt stores the template extension which will build
  37. beeTemplateExt = []string{"tpl", "html", "gohtml"}
  38. // beeTemplatePreprocessors stores associations of extension -> preprocessor handler
  39. beeTemplateEngines = map[string]templatePreProcessor{}
  40. beeTemplateFS = defaultFSFunc
  41. )
  42. // ExecuteTemplate applies the template with name to the specified data object,
  43. // writing the output to wr.
  44. // A template will be executed safely in parallel.
  45. func ExecuteTemplate(wr io.Writer, name string, data interface{}) error {
  46. return ExecuteViewPathTemplate(wr, name, BConfig.WebConfig.ViewsPath, data)
  47. }
  48. // ExecuteViewPathTemplate applies the template with name and from specific viewPath to the specified data object,
  49. // writing the output to wr.
  50. // A template will be executed safely in parallel.
  51. func ExecuteViewPathTemplate(wr io.Writer, name string, viewPath string, data interface{}) error {
  52. if BConfig.RunMode == DEV {
  53. templatesLock.RLock()
  54. defer templatesLock.RUnlock()
  55. }
  56. if beeTemplates, ok := beeViewPathTemplates[viewPath]; ok {
  57. if t, ok := beeTemplates[name]; ok {
  58. var err error
  59. if t.Lookup(name) != nil {
  60. err = t.ExecuteTemplate(wr, name, data)
  61. } else {
  62. err = t.Execute(wr, data)
  63. }
  64. if err != nil {
  65. logs.Trace("template Execute err:", err)
  66. }
  67. return err
  68. }
  69. panic("can't find templatefile in the path:" + viewPath + "/" + name)
  70. }
  71. panic("Unknown view path:" + viewPath)
  72. }
  73. func init() {
  74. beegoTplFuncMap["dateformat"] = DateFormat
  75. beegoTplFuncMap["date"] = Date
  76. beegoTplFuncMap["compare"] = Compare
  77. beegoTplFuncMap["compare_not"] = CompareNot
  78. beegoTplFuncMap["not_nil"] = NotNil
  79. beegoTplFuncMap["not_null"] = NotNil
  80. beegoTplFuncMap["substr"] = Substr
  81. beegoTplFuncMap["html2str"] = HTML2str
  82. beegoTplFuncMap["str2html"] = Str2html
  83. beegoTplFuncMap["htmlquote"] = Htmlquote
  84. beegoTplFuncMap["htmlunquote"] = Htmlunquote
  85. beegoTplFuncMap["renderform"] = RenderForm
  86. beegoTplFuncMap["assets_js"] = AssetsJs
  87. beegoTplFuncMap["assets_css"] = AssetsCSS
  88. beegoTplFuncMap["config"] = GetConfig
  89. beegoTplFuncMap["map_get"] = MapGet
  90. // Comparisons
  91. beegoTplFuncMap["eq"] = eq // ==
  92. beegoTplFuncMap["ge"] = ge // >=
  93. beegoTplFuncMap["gt"] = gt // >
  94. beegoTplFuncMap["le"] = le // <=
  95. beegoTplFuncMap["lt"] = lt // <
  96. beegoTplFuncMap["ne"] = ne // !=
  97. beegoTplFuncMap["urlfor"] = URLFor // build a URL to match a Controller and it's method
  98. }
  99. // AddFuncMap let user to register a func in the template.
  100. func AddFuncMap(key string, fn interface{}) error {
  101. beegoTplFuncMap[key] = fn
  102. return nil
  103. }
  104. type templatePreProcessor func(root, path string, funcs template.FuncMap) (*template.Template, error)
  105. type templateFile struct {
  106. root string
  107. files map[string][]string
  108. }
  109. // visit will make the paths into two part,the first is subDir (without tf.root),the second is full path(without tf.root).
  110. // if tf.root="views" and
  111. // paths is "views/errors/404.html",the subDir will be "errors",the file will be "errors/404.html"
  112. // paths is "views/admin/errors/404.html",the subDir will be "admin/errors",the file will be "admin/errors/404.html"
  113. func (tf *templateFile) visit(paths string, f os.FileInfo, err error) error {
  114. if f == nil {
  115. return err
  116. }
  117. if f.IsDir() || (f.Mode()&os.ModeSymlink) > 0 {
  118. return nil
  119. }
  120. if !HasTemplateExt(paths) {
  121. return nil
  122. }
  123. replace := strings.NewReplacer("\\", "/")
  124. file := strings.TrimLeft(replace.Replace(paths[len(tf.root):]), "/")
  125. subDir := filepath.Dir(file)
  126. tf.files[subDir] = append(tf.files[subDir], file)
  127. return nil
  128. }
  129. // HasTemplateExt return this path contains supported template extension of beego or not.
  130. func HasTemplateExt(paths string) bool {
  131. for _, v := range beeTemplateExt {
  132. if strings.HasSuffix(paths, "."+v) {
  133. return true
  134. }
  135. }
  136. return false
  137. }
  138. // AddTemplateExt add new extension for template.
  139. func AddTemplateExt(ext string) {
  140. for _, v := range beeTemplateExt {
  141. if v == ext {
  142. return
  143. }
  144. }
  145. beeTemplateExt = append(beeTemplateExt, ext)
  146. }
  147. // AddViewPath adds a new path to the supported view paths.
  148. //Can later be used by setting a controller ViewPath to this folder
  149. //will panic if called after beego.Run()
  150. func AddViewPath(viewPath string) error {
  151. if beeViewPathTemplateLocked {
  152. if _, exist := beeViewPathTemplates[viewPath]; exist {
  153. return nil //Ignore if viewpath already exists
  154. }
  155. panic("Can not add new view paths after beego.Run()")
  156. }
  157. beeViewPathTemplates[viewPath] = make(map[string]*template.Template)
  158. return BuildTemplate(viewPath)
  159. }
  160. func lockViewPaths() {
  161. beeViewPathTemplateLocked = true
  162. }
  163. // BuildTemplate will build all template files in a directory.
  164. // it makes beego can render any template file in view directory.
  165. func BuildTemplate(dir string, files ...string) error {
  166. var err error
  167. fs := beeTemplateFS()
  168. f, err := fs.Open(dir)
  169. if err != nil {
  170. if os.IsNotExist(err) {
  171. return nil
  172. }
  173. return errors.New("dir open err")
  174. }
  175. defer f.Close()
  176. beeTemplates, ok := beeViewPathTemplates[dir]
  177. if !ok {
  178. panic("Unknown view path: " + dir)
  179. }
  180. self := &templateFile{
  181. root: dir,
  182. files: make(map[string][]string),
  183. }
  184. err = Walk(fs, dir, func(path string, f os.FileInfo, err error) error {
  185. return self.visit(path, f, err)
  186. })
  187. if err != nil {
  188. fmt.Printf("Walk() returned %v\n", err)
  189. return err
  190. }
  191. buildAllFiles := len(files) == 0
  192. for _, v := range self.files {
  193. for _, file := range v {
  194. if buildAllFiles || utils.InSlice(file, files) {
  195. templatesLock.Lock()
  196. ext := filepath.Ext(file)
  197. var t *template.Template
  198. if len(ext) == 0 {
  199. t, err = getTemplate(self.root, fs, file, v...)
  200. } else if fn, ok := beeTemplateEngines[ext[1:]]; ok {
  201. t, err = fn(self.root, file, beegoTplFuncMap)
  202. } else {
  203. t, err = getTemplate(self.root, fs, file, v...)
  204. }
  205. if err != nil {
  206. logs.Error("parse template err:", file, err)
  207. templatesLock.Unlock()
  208. return err
  209. }
  210. beeTemplates[file] = t
  211. templatesLock.Unlock()
  212. }
  213. }
  214. }
  215. return nil
  216. }
  217. func getTplDeep(root string, fs http.FileSystem, file string, parent string, t *template.Template) (*template.Template, [][]string, error) {
  218. var fileAbsPath string
  219. var rParent string
  220. var err error
  221. if strings.HasPrefix(file, "../") {
  222. rParent = filepath.Join(filepath.Dir(parent), file)
  223. fileAbsPath = filepath.Join(root, filepath.Dir(parent), file)
  224. } else {
  225. rParent = file
  226. fileAbsPath = filepath.Join(root, file)
  227. }
  228. f, err := fs.Open(fileAbsPath)
  229. if err != nil {
  230. panic("can't find template file:" + file)
  231. }
  232. defer f.Close()
  233. data, err := ioutil.ReadAll(f)
  234. if err != nil {
  235. return nil, [][]string{}, err
  236. }
  237. t, err = t.New(file).Parse(string(data))
  238. if err != nil {
  239. return nil, [][]string{}, err
  240. }
  241. reg := regexp.MustCompile(BConfig.WebConfig.TemplateLeft + "[ ]*template[ ]+\"([^\"]+)\"")
  242. allSub := reg.FindAllStringSubmatch(string(data), -1)
  243. for _, m := range allSub {
  244. if len(m) == 2 {
  245. tl := t.Lookup(m[1])
  246. if tl != nil {
  247. continue
  248. }
  249. if !HasTemplateExt(m[1]) {
  250. continue
  251. }
  252. _, _, err = getTplDeep(root, fs, m[1], rParent, t)
  253. if err != nil {
  254. return nil, [][]string{}, err
  255. }
  256. }
  257. }
  258. return t, allSub, nil
  259. }
  260. func getTemplate(root string, fs http.FileSystem, file string, others ...string) (t *template.Template, err error) {
  261. t = template.New(file).Delims(BConfig.WebConfig.TemplateLeft, BConfig.WebConfig.TemplateRight).Funcs(beegoTplFuncMap)
  262. var subMods [][]string
  263. t, subMods, err = getTplDeep(root, fs, file, "", t)
  264. if err != nil {
  265. return nil, err
  266. }
  267. t, err = _getTemplate(t, root, fs, subMods, others...)
  268. if err != nil {
  269. return nil, err
  270. }
  271. return
  272. }
  273. func _getTemplate(t0 *template.Template, root string, fs http.FileSystem, subMods [][]string, others ...string) (t *template.Template, err error) {
  274. t = t0
  275. for _, m := range subMods {
  276. if len(m) == 2 {
  277. tpl := t.Lookup(m[1])
  278. if tpl != nil {
  279. continue
  280. }
  281. //first check filename
  282. for _, otherFile := range others {
  283. if otherFile == m[1] {
  284. var subMods1 [][]string
  285. t, subMods1, err = getTplDeep(root, fs, otherFile, "", t)
  286. if err != nil {
  287. logs.Trace("template parse file err:", err)
  288. } else if len(subMods1) > 0 {
  289. t, err = _getTemplate(t, root, fs, subMods1, others...)
  290. }
  291. break
  292. }
  293. }
  294. //second check define
  295. for _, otherFile := range others {
  296. var data []byte
  297. fileAbsPath := filepath.Join(root, otherFile)
  298. f, err := fs.Open(fileAbsPath)
  299. if err != nil {
  300. f.Close()
  301. logs.Trace("template file parse error, not success open file:", err)
  302. continue
  303. }
  304. data, err = ioutil.ReadAll(f)
  305. f.Close()
  306. if err != nil {
  307. logs.Trace("template file parse error, not success read file:", err)
  308. continue
  309. }
  310. reg := regexp.MustCompile(BConfig.WebConfig.TemplateLeft + "[ ]*define[ ]+\"([^\"]+)\"")
  311. allSub := reg.FindAllStringSubmatch(string(data), -1)
  312. for _, sub := range allSub {
  313. if len(sub) == 2 && sub[1] == m[1] {
  314. var subMods1 [][]string
  315. t, subMods1, err = getTplDeep(root, fs, otherFile, "", t)
  316. if err != nil {
  317. logs.Trace("template parse file err:", err)
  318. } else if len(subMods1) > 0 {
  319. t, err = _getTemplate(t, root, fs, subMods1, others...)
  320. if err != nil {
  321. logs.Trace("template parse file err:", err)
  322. }
  323. }
  324. break
  325. }
  326. }
  327. }
  328. }
  329. }
  330. return
  331. }
  332. type templateFSFunc func() http.FileSystem
  333. func defaultFSFunc() http.FileSystem {
  334. return FileSystem{}
  335. }
  336. // SetTemplateFSFunc set default filesystem function
  337. func SetTemplateFSFunc(fnt templateFSFunc) {
  338. beeTemplateFS = fnt
  339. }
  340. // SetViewsPath sets view directory path in beego application.
  341. func SetViewsPath(path string) *App {
  342. BConfig.WebConfig.ViewsPath = path
  343. return BeeApp
  344. }
  345. // SetStaticPath sets static directory path and proper url pattern in beego application.
  346. // if beego.SetStaticPath("static","public"), visit /static/* to load static file in folder "public".
  347. func SetStaticPath(url string, path string) *App {
  348. if !strings.HasPrefix(url, "/") {
  349. url = "/" + url
  350. }
  351. if url != "/" {
  352. url = strings.TrimRight(url, "/")
  353. }
  354. BConfig.WebConfig.StaticDir[url] = path
  355. return BeeApp
  356. }
  357. // DelStaticPath removes the static folder setting in this url pattern in beego application.
  358. func DelStaticPath(url string) *App {
  359. if !strings.HasPrefix(url, "/") {
  360. url = "/" + url
  361. }
  362. if url != "/" {
  363. url = strings.TrimRight(url, "/")
  364. }
  365. delete(BConfig.WebConfig.StaticDir, url)
  366. return BeeApp
  367. }
  368. // AddTemplateEngine add a new templatePreProcessor which support extension
  369. func AddTemplateEngine(extension string, fn templatePreProcessor) *App {
  370. AddTemplateExt(extension)
  371. beeTemplateEngines[extension] = fn
  372. return BeeApp
  373. }