template.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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/cnlh/nps/vender/github.com/astaxie/beego/logs"
  27. "github.com/cnlh/nps/vender/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("Unknown 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. if _, exist := beeViewPathTemplates[viewPath]; exist {
  151. return nil //Ignore if viewpath already exists
  152. }
  153. panic("Can not add new view paths after beego.Run()")
  154. }
  155. beeViewPathTemplates[viewPath] = make(map[string]*template.Template)
  156. return BuildTemplate(viewPath)
  157. }
  158. func lockViewPaths() {
  159. beeViewPathTemplateLocked = true
  160. }
  161. // BuildTemplate will build all template files in a directory.
  162. // it makes beego can render any template file in view directory.
  163. func BuildTemplate(dir string, files ...string) error {
  164. if _, err := os.Stat(dir); err != nil {
  165. if os.IsNotExist(err) {
  166. return nil
  167. }
  168. return errors.New("dir open err")
  169. }
  170. beeTemplates, ok := beeViewPathTemplates[dir]
  171. if !ok {
  172. panic("Unknown view path: " + dir)
  173. }
  174. self := &templateFile{
  175. root: dir,
  176. files: make(map[string][]string),
  177. }
  178. err := filepath.Walk(dir, func(path string, f os.FileInfo, err error) error {
  179. return self.visit(path, f, err)
  180. })
  181. if err != nil {
  182. fmt.Printf("filepath.Walk() returned %v\n", err)
  183. return err
  184. }
  185. buildAllFiles := len(files) == 0
  186. for _, v := range self.files {
  187. for _, file := range v {
  188. if buildAllFiles || utils.InSlice(file, files) {
  189. templatesLock.Lock()
  190. ext := filepath.Ext(file)
  191. var t *template.Template
  192. if len(ext) == 0 {
  193. t, err = getTemplate(self.root, file, v...)
  194. } else if fn, ok := beeTemplateEngines[ext[1:]]; ok {
  195. t, err = fn(self.root, file, beegoTplFuncMap)
  196. } else {
  197. t, err = getTemplate(self.root, file, v...)
  198. }
  199. if err != nil {
  200. logs.Error("parse template err:", file, err)
  201. templatesLock.Unlock()
  202. return err
  203. }
  204. beeTemplates[file] = t
  205. templatesLock.Unlock()
  206. }
  207. }
  208. }
  209. return nil
  210. }
  211. func getTplDeep(root, file, parent string, t *template.Template) (*template.Template, [][]string, error) {
  212. var fileAbsPath string
  213. var rParent string
  214. if filepath.HasPrefix(file, "../") {
  215. rParent = filepath.Join(filepath.Dir(parent), file)
  216. fileAbsPath = filepath.Join(root, filepath.Dir(parent), file)
  217. } else {
  218. rParent = file
  219. fileAbsPath = filepath.Join(root, file)
  220. }
  221. if e := utils.FileExists(fileAbsPath); !e {
  222. panic("can't find template file:" + file)
  223. }
  224. data, err := ioutil.ReadFile(fileAbsPath)
  225. if err != nil {
  226. return nil, [][]string{}, err
  227. }
  228. t, err = t.New(file).Parse(string(data))
  229. if err != nil {
  230. return nil, [][]string{}, err
  231. }
  232. reg := regexp.MustCompile(BConfig.WebConfig.TemplateLeft + "[ ]*template[ ]+\"([^\"]+)\"")
  233. allSub := reg.FindAllStringSubmatch(string(data), -1)
  234. for _, m := range allSub {
  235. if len(m) == 2 {
  236. tl := t.Lookup(m[1])
  237. if tl != nil {
  238. continue
  239. }
  240. if !HasTemplateExt(m[1]) {
  241. continue
  242. }
  243. _, _, err = getTplDeep(root, m[1], rParent, t)
  244. if err != nil {
  245. return nil, [][]string{}, err
  246. }
  247. }
  248. }
  249. return t, allSub, nil
  250. }
  251. func getTemplate(root, file string, others ...string) (t *template.Template, err error) {
  252. t = template.New(file).Delims(BConfig.WebConfig.TemplateLeft, BConfig.WebConfig.TemplateRight).Funcs(beegoTplFuncMap)
  253. var subMods [][]string
  254. t, subMods, err = getTplDeep(root, file, "", t)
  255. if err != nil {
  256. return nil, err
  257. }
  258. t, err = _getTemplate(t, root, subMods, others...)
  259. if err != nil {
  260. return nil, err
  261. }
  262. return
  263. }
  264. func _getTemplate(t0 *template.Template, root string, subMods [][]string, others ...string) (t *template.Template, err error) {
  265. t = t0
  266. for _, m := range subMods {
  267. if len(m) == 2 {
  268. tpl := t.Lookup(m[1])
  269. if tpl != nil {
  270. continue
  271. }
  272. //first check filename
  273. for _, otherFile := range others {
  274. if otherFile == m[1] {
  275. var subMods1 [][]string
  276. t, subMods1, err = getTplDeep(root, otherFile, "", t)
  277. if err != nil {
  278. logs.Trace("template parse file err:", err)
  279. } else if len(subMods1) > 0 {
  280. t, err = _getTemplate(t, root, subMods1, others...)
  281. }
  282. break
  283. }
  284. }
  285. //second check define
  286. for _, otherFile := range others {
  287. var data []byte
  288. fileAbsPath := filepath.Join(root, otherFile)
  289. data, err = ioutil.ReadFile(fileAbsPath)
  290. if err != nil {
  291. continue
  292. }
  293. reg := regexp.MustCompile(BConfig.WebConfig.TemplateLeft + "[ ]*define[ ]+\"([^\"]+)\"")
  294. allSub := reg.FindAllStringSubmatch(string(data), -1)
  295. for _, sub := range allSub {
  296. if len(sub) == 2 && sub[1] == m[1] {
  297. var subMods1 [][]string
  298. t, subMods1, err = getTplDeep(root, otherFile, "", t)
  299. if err != nil {
  300. logs.Trace("template parse file err:", err)
  301. } else if len(subMods1) > 0 {
  302. t, err = _getTemplate(t, root, subMods1, others...)
  303. }
  304. break
  305. }
  306. }
  307. }
  308. }
  309. }
  310. return
  311. }
  312. // SetViewsPath sets view directory path in beego application.
  313. func SetViewsPath(path string) *App {
  314. BConfig.WebConfig.ViewsPath = path
  315. return BeeApp
  316. }
  317. // SetStaticPath sets static directory path and proper url pattern in beego application.
  318. // if beego.SetStaticPath("static","public"), visit /static/* to load static file in folder "public".
  319. func SetStaticPath(url string, path string) *App {
  320. if !strings.HasPrefix(url, "/") {
  321. url = "/" + url
  322. }
  323. if url != "/" {
  324. url = strings.TrimRight(url, "/")
  325. }
  326. BConfig.WebConfig.StaticDir[url] = path
  327. return BeeApp
  328. }
  329. // DelStaticPath removes the static folder setting in this url pattern in beego application.
  330. func DelStaticPath(url string) *App {
  331. if !strings.HasPrefix(url, "/") {
  332. url = "/" + url
  333. }
  334. if url != "/" {
  335. url = strings.TrimRight(url, "/")
  336. }
  337. delete(BConfig.WebConfig.StaticDir, url)
  338. return BeeApp
  339. }
  340. // AddTemplateEngine add a new templatePreProcessor which support extension
  341. func AddTemplateEngine(extension string, fn templatePreProcessor) *App {
  342. AddTemplateExt(extension)
  343. beeTemplateEngines[extension] = fn
  344. return BeeApp
  345. }