template.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. // Copyright 2016 José Santos <henrique_1609@me.com>
  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. // Jet is a fast and dynamic template engine for the Go programming language, set of features
  15. // includes very fast template execution, a dynamic and flexible language, template inheritance, low number of allocations,
  16. // special interfaces to allow even further optimizations.
  17. package jet
  18. import (
  19. "fmt"
  20. "io"
  21. "io/ioutil"
  22. "path"
  23. "reflect"
  24. "strings"
  25. "sync"
  26. "text/template"
  27. )
  28. // Set is responsible to load,invoke parse and cache templates and relations
  29. // every jet template is associated with one set.
  30. // create a set with jet.NewSet(escapeeFn) returns a pointer to the Set
  31. type Set struct {
  32. loader Loader
  33. templates map[string]*Template // parsed templates
  34. escapee SafeWriter // escapee to use at runtime
  35. globals VarMap // global scope for this template set
  36. tmx *sync.RWMutex // template parsing mutex
  37. gmx *sync.RWMutex // global variables map mutex
  38. defaultExtensions []string
  39. developmentMode bool
  40. }
  41. // SetDevelopmentMode set's development mode on/off, in development mode template will be recompiled on every run
  42. func (s *Set) SetDevelopmentMode(b bool) *Set {
  43. s.developmentMode = b
  44. return s
  45. }
  46. func (a *Set) LookupGlobal(key string) (val interface{}, found bool) {
  47. a.gmx.RLock()
  48. val, found = a.globals[key]
  49. a.gmx.RUnlock()
  50. return
  51. }
  52. // AddGlobal add or set a global variable into the Set
  53. func (s *Set) AddGlobal(key string, i interface{}) *Set {
  54. s.gmx.Lock()
  55. if s.globals == nil {
  56. s.globals = make(VarMap)
  57. }
  58. s.globals[key] = reflect.ValueOf(i)
  59. s.gmx.Unlock()
  60. return s
  61. }
  62. func (s *Set) AddGlobalFunc(key string, fn Func) *Set {
  63. return s.AddGlobal(key, fn)
  64. }
  65. // NewSetLoader creates a new set with custom Loader
  66. func NewSetLoader(escapee SafeWriter, loader Loader) *Set {
  67. return &Set{loader: loader, tmx: &sync.RWMutex{}, gmx: &sync.RWMutex{}, escapee: escapee, templates: make(map[string]*Template), defaultExtensions: append([]string{}, defaultExtensions...)}
  68. }
  69. // NewHTMLSetLoader creates a new set with custom Loader
  70. func NewHTMLSetLoader(loader Loader) *Set {
  71. return NewSetLoader(template.HTMLEscape, loader)
  72. }
  73. // NewSet creates a new set, dirs is a list of directories to be searched for templates
  74. func NewSet(escapee SafeWriter, dirs ...string) *Set {
  75. return NewSetLoader(escapee, &OSFileSystemLoader{dirs: dirs})
  76. }
  77. // NewHTMLSet creates a new set, dirs is a list of directories to be searched for templates
  78. func NewHTMLSet(dirs ...string) *Set {
  79. return NewSet(template.HTMLEscape, dirs...)
  80. }
  81. // AddPath add path to the lookup list, when loading a template the Set will
  82. // look into the lookup list for the file matching the provided name.
  83. func (s *Set) AddPath(path string) {
  84. if loader, ok := s.loader.(hasAddPath); ok {
  85. loader.AddPath(path)
  86. } else {
  87. panic(fmt.Sprintf("AddPath() not supported on custom loader of type %T", s.loader))
  88. }
  89. }
  90. // AddGopathPath add path based on GOPATH env to the lookup list, when loading a template the Set will
  91. // look into the lookup list for the file matching the provided name.
  92. func (s *Set) AddGopathPath(path string) {
  93. if loader, ok := s.loader.(hasAddGopathPath); ok {
  94. loader.AddGopathPath(path)
  95. } else {
  96. panic(fmt.Sprintf("AddGopathPath() not supported on custom loader of type %T", s.loader))
  97. }
  98. }
  99. // resolveName try to resolve a template name, the steps as follow
  100. // 1. try provided path
  101. // 2. try provided path+defaultExtensions
  102. // ex: set.resolveName("catalog/products.list") with defaultExtensions set to []string{".html.jet",".jet"}
  103. // try catalog/products.list
  104. // try catalog/products.list.html.jet
  105. // try catalog/products.list.jet
  106. func (s *Set) resolveName(name string) (newName, fileName string, foundLoaded, foundFile bool) {
  107. newName = name
  108. if _, foundLoaded = s.templates[newName]; foundLoaded {
  109. return
  110. }
  111. if fileName, foundFile = s.loader.Exists(name); foundFile {
  112. return
  113. }
  114. for _, extension := range s.defaultExtensions {
  115. newName = name + extension
  116. if _, foundLoaded = s.templates[newName]; foundLoaded {
  117. return
  118. }
  119. if fileName, foundFile = s.loader.Exists(newName); foundFile {
  120. return
  121. }
  122. }
  123. return
  124. }
  125. func (s *Set) resolveNameSibling(name, sibling string) (newName, fileName string, foundLoaded, foundFile, isRelativeName bool) {
  126. if sibling != "" {
  127. i := strings.LastIndex(sibling, "/")
  128. if i != -1 {
  129. if newName, fileName, foundLoaded, foundFile = s.resolveName(path.Join(sibling[:i+1], name)); foundFile || foundLoaded {
  130. isRelativeName = true
  131. return
  132. }
  133. }
  134. }
  135. newName, fileName, foundLoaded, foundFile = s.resolveName(name)
  136. return
  137. }
  138. // Parse parses the template, this method will link the template to the set but not the set to
  139. func (s *Set) Parse(name, content string) (*Template, error) {
  140. sc := *s
  141. sc.developmentMode = true
  142. sc.tmx.RLock()
  143. t, err := sc.parse(name, content)
  144. sc.tmx.RUnlock()
  145. return t, err
  146. }
  147. func (s *Set) loadFromFile(name, fileName string) (template *Template, err error) {
  148. f, err := s.loader.Open(fileName)
  149. if err != nil {
  150. return nil, err
  151. }
  152. defer f.Close()
  153. content, err := ioutil.ReadAll(f)
  154. if err != nil {
  155. return nil, err
  156. }
  157. return s.parse(name, string(content))
  158. }
  159. func (s *Set) getTemplateWhileParsing(parentName, name string) (template *Template, err error) {
  160. name = path.Clean(name)
  161. if s.developmentMode {
  162. if newName, fileName, _, foundPath, _ := s.resolveNameSibling(name, parentName); foundPath {
  163. return s.loadFromFile(newName, fileName)
  164. } else {
  165. return nil, fmt.Errorf("template %s can't be loaded", name)
  166. }
  167. }
  168. if newName, fileName, foundLoaded, foundPath, isRelative := s.resolveNameSibling(name, parentName); foundPath {
  169. template, err = s.loadFromFile(newName, fileName)
  170. s.templates[newName] = template
  171. if !isRelative {
  172. s.templates[name] = template
  173. }
  174. } else if foundLoaded {
  175. template = s.templates[newName]
  176. if !isRelative && name != newName {
  177. s.templates[name] = template
  178. }
  179. } else {
  180. err = fmt.Errorf("template %s can't be loaded", name)
  181. }
  182. return
  183. }
  184. // getTemplate gets a template already loaded by name
  185. func (s *Set) getTemplate(name, sibling string) (template *Template, err error) {
  186. name = path.Clean(name)
  187. if s.developmentMode {
  188. s.tmx.RLock()
  189. defer s.tmx.RUnlock()
  190. if newName, fileName, foundLoaded, foundFile, _ := s.resolveNameSibling(name, sibling); foundFile || foundLoaded {
  191. if foundFile {
  192. template, err = s.loadFromFile(newName, fileName)
  193. } else {
  194. template, _ = s.templates[newName]
  195. }
  196. } else {
  197. err = fmt.Errorf("template %s can't be loaded", name)
  198. }
  199. return
  200. }
  201. //fast path
  202. s.tmx.RLock()
  203. newName, fileName, foundLoaded, foundFile, isRelative := s.resolveNameSibling(name, sibling)
  204. if foundLoaded {
  205. template = s.templates[newName]
  206. s.tmx.RUnlock()
  207. if !isRelative && name != newName {
  208. // creates an alias
  209. s.tmx.Lock()
  210. if _, found := s.templates[name]; !found {
  211. s.templates[name] = template
  212. }
  213. s.tmx.Unlock()
  214. }
  215. return
  216. }
  217. s.tmx.RUnlock()
  218. //not found parses and cache
  219. s.tmx.Lock()
  220. defer s.tmx.Unlock()
  221. newName, fileName, foundLoaded, foundFile, isRelative = s.resolveNameSibling(name, sibling)
  222. if foundLoaded {
  223. template = s.templates[newName]
  224. if !isRelative && name != newName {
  225. // creates an alias
  226. if _, found := s.templates[name]; !found {
  227. s.templates[name] = template
  228. }
  229. }
  230. } else if foundFile {
  231. template, err = s.loadFromFile(newName, fileName)
  232. if !isRelative && name != newName {
  233. // creates an alias
  234. if _, found := s.templates[name]; !found {
  235. s.templates[name] = template
  236. }
  237. }
  238. s.templates[newName] = template
  239. } else {
  240. err = fmt.Errorf("template %s can't be loaded", name)
  241. }
  242. return
  243. }
  244. func (s *Set) GetTemplate(name string) (template *Template, err error) {
  245. template, err = s.getTemplate(name, "")
  246. return
  247. }
  248. func (s *Set) LoadTemplate(name, content string) (template *Template, err error) {
  249. if s.developmentMode {
  250. s.tmx.RLock()
  251. defer s.tmx.RUnlock()
  252. template, err = s.parse(name, content)
  253. return
  254. }
  255. //fast path
  256. var found bool
  257. s.tmx.RLock()
  258. if template, found = s.templates[name]; found {
  259. s.tmx.RUnlock()
  260. return
  261. }
  262. s.tmx.RUnlock()
  263. //not found parses and cache
  264. s.tmx.Lock()
  265. defer s.tmx.Unlock()
  266. if template, found = s.templates[name]; found {
  267. return
  268. }
  269. if template, err = s.parse(name, content); err == nil {
  270. s.templates[name] = template
  271. }
  272. return
  273. }
  274. func (t *Template) String() (template string) {
  275. if t.extends != nil {
  276. if len(t.Root.Nodes) > 0 && len(t.imports) == 0 {
  277. template += fmt.Sprintf("{{extends %q}}", t.extends.ParseName)
  278. } else {
  279. template += fmt.Sprintf("{{extends %q}}", t.extends.ParseName)
  280. }
  281. }
  282. for k, _import := range t.imports {
  283. if t.extends == nil && k == 0 {
  284. template += fmt.Sprintf("{{import %q}}", _import.ParseName)
  285. } else {
  286. template += fmt.Sprintf("\n{{import %q}}", _import.ParseName)
  287. }
  288. }
  289. if t.extends != nil || len(t.imports) > 0 {
  290. if len(t.Root.Nodes) > 0 {
  291. template += "\n" + t.Root.String()
  292. }
  293. } else {
  294. template += t.Root.String()
  295. }
  296. return
  297. }
  298. func (t *Template) addBlocks(blocks map[string]*BlockNode) {
  299. if len(blocks) > 0 {
  300. if t.processedBlocks == nil {
  301. t.processedBlocks = make(map[string]*BlockNode)
  302. }
  303. for key, value := range blocks {
  304. t.processedBlocks[key] = value
  305. }
  306. }
  307. }
  308. type VarMap map[string]reflect.Value
  309. func (scope VarMap) Set(name string, v interface{}) VarMap {
  310. scope[name] = reflect.ValueOf(v)
  311. return scope
  312. }
  313. func (scope VarMap) SetFunc(name string, v Func) VarMap {
  314. scope[name] = reflect.ValueOf(v)
  315. return scope
  316. }
  317. func (scope VarMap) SetWriter(name string, v SafeWriter) VarMap {
  318. scope[name] = reflect.ValueOf(v)
  319. return scope
  320. }
  321. // Execute executes the template in the w Writer
  322. func (t *Template) Execute(w io.Writer, variables VarMap, data interface{}) error {
  323. return t.ExecuteI18N(nil, w, variables, data)
  324. }
  325. type Translator interface {
  326. Msg(key, defaultValue string) string
  327. Trans(format, defaultFormat string, v ...interface{}) string
  328. }
  329. func (t *Template) ExecuteI18N(translator Translator, w io.Writer, variables VarMap, data interface{}) (err error) {
  330. st := pool_State.Get().(*Runtime)
  331. defer st.recover(&err)
  332. st.blocks = t.processedBlocks
  333. st.translator = translator
  334. st.variables = variables
  335. st.set = t.set
  336. st.Writer = w
  337. // resolve extended template
  338. for t.extends != nil {
  339. t = t.extends
  340. }
  341. if data != nil {
  342. st.context = reflect.ValueOf(data)
  343. }
  344. st.executeList(t.Root)
  345. return
  346. }