ace.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package view
  2. import (
  3. "path"
  4. "sync"
  5. "github.com/yosssi/ace"
  6. )
  7. // Ace returns a new ace view engine.
  8. // It shares the same exactly logic with the
  9. // html view engine, it uses the same exactly configuration.
  10. // The given "extension" MUST begin with a dot.
  11. //
  12. // Read more about the Ace Go Parser: https://github.com/yosssi/ace
  13. func Ace(directory, extension string) *HTMLEngine {
  14. s := HTML(directory, extension)
  15. funcs := make(map[string]interface{}, 0)
  16. once := new(sync.Once)
  17. s.middleware = func(name string, text []byte) (contents string, err error) {
  18. once.Do(func() { // on first template parse, all funcs are given.
  19. for k, v := range emptyFuncs {
  20. funcs[k] = v
  21. }
  22. for k, v := range s.funcs {
  23. funcs[k] = v
  24. }
  25. })
  26. name = path.Join(path.Clean(directory), name)
  27. src := ace.NewSource(
  28. ace.NewFile(name, text),
  29. ace.NewFile("", []byte{}),
  30. []*ace.File{},
  31. )
  32. rslt, err := ace.ParseSource(src, nil)
  33. if err != nil {
  34. return "", err
  35. }
  36. t, err := ace.CompileResult(name, rslt, &ace.Options{
  37. Extension: extension[1:],
  38. FuncMap: funcs,
  39. DelimLeft: s.left,
  40. DelimRight: s.right,
  41. })
  42. if err != nil {
  43. return "", err
  44. }
  45. return t.Lookup(name).Tree.Root.String(), nil
  46. }
  47. return s
  48. }