ace.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package ace
  2. import (
  3. "html/template"
  4. "sync"
  5. )
  6. var cache = make(map[string]template.Template)
  7. var cacheMutex = new(sync.RWMutex)
  8. // Load loads and returns an HTML template. Each Ace templates are parsed only once
  9. // and cached if the "DynamicReload" option are not set.
  10. func Load(basePath, innerPath string, opts *Options) (*template.Template, error) {
  11. // Initialize the options.
  12. opts = InitializeOptions(opts)
  13. name := basePath + colon + innerPath
  14. if !opts.DynamicReload {
  15. if tpl, ok := getCache(name); ok {
  16. return &tpl, nil
  17. }
  18. }
  19. // Read files.
  20. src, err := readFiles(basePath, innerPath, opts)
  21. if err != nil {
  22. return nil, err
  23. }
  24. // Parse the source.
  25. rslt, err := ParseSource(src, opts)
  26. if err != nil {
  27. return nil, err
  28. }
  29. // Compile the parsed result.
  30. tpl, err := CompileResult(name, rslt, opts)
  31. if err != nil {
  32. return nil, err
  33. }
  34. if !opts.DynamicReload {
  35. setCache(name, *tpl)
  36. }
  37. return tpl, nil
  38. }
  39. // getCache returns the cached template.
  40. func getCache(name string) (template.Template, bool) {
  41. cacheMutex.RLock()
  42. tpl, ok := cache[name]
  43. cacheMutex.RUnlock()
  44. return tpl, ok
  45. }
  46. // setCache sets the template to the cache.
  47. func setCache(name string, tpl template.Template) {
  48. cacheMutex.Lock()
  49. cache[name] = tpl
  50. cacheMutex.Unlock()
  51. }
  52. // FlushCache clears all cached templates.
  53. func FlushCache() {
  54. cacheMutex.Lock()
  55. cache = make(map[string]template.Template)
  56. cacheMutex.Unlock()
  57. }