funcs.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package blocks
  2. import "html/template"
  3. var builtins = template.FuncMap{
  4. "partial": func(v *Blocks) interface{} {
  5. return v.PartialFunc
  6. },
  7. }
  8. // Register register a function map
  9. // that will be available across all Blocks view engines.
  10. // The values (functions) should be compatible
  11. // with a standard html/template function, however
  12. // as a special feature, the function input's can be a type of
  13. // func(*Blocks) (fn interface{}) or func(*Blocks) template.FuncMap as well,
  14. // so it can use the current engine's methods such as `ParseTemplate`.
  15. // It's legal to override previous functions.
  16. //
  17. // It is used like the `database/sql.Register` function.
  18. //
  19. // Usage:
  20. //
  21. // package myFuncsCollection1
  22. // func init() {
  23. // blocks.Register(a_funcMap)
  24. // }
  25. //
  26. // package myFuncsCollection2
  27. // func init() {
  28. // blocks.Register(anothrer_funcMap)
  29. // }
  30. //
  31. // package main
  32. // import _ "myFuncsCollection1"
  33. // import _ "myFuncsCollection2"
  34. //
  35. // func main() {
  36. // views := blocks.New("./views")
  37. // }
  38. // Views contains the functions of both collections.
  39. func Register(funcMap template.FuncMap) {
  40. for name, fn := range funcMap {
  41. builtins[name] = fn
  42. }
  43. }
  44. func translateFuncs(v *Blocks, funcMap template.FuncMap) template.FuncMap { // used on `New`.
  45. funcs := make(template.FuncMap)
  46. for name, fn := range funcMap {
  47. if fn == nil {
  48. continue
  49. }
  50. switch f := fn.(type) {
  51. case func(*Blocks) interface{}:
  52. funcs[name] = f(v)
  53. case func(*Blocks) template.FuncMap:
  54. for deepName, deepFn := range translateFuncs(v, f(v)) {
  55. funcs[deepName] = deepFn
  56. }
  57. default:
  58. funcs[name] = fn
  59. }
  60. }
  61. return funcs
  62. }