1
0

template.go 10 KB

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