view.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package view
  2. import (
  3. "io"
  4. "path/filepath"
  5. "github.com/kataras/iris/core/errors"
  6. )
  7. // View is responsible to
  8. // load the correct templates
  9. // for each of the registered view engines.
  10. type View struct {
  11. engines []Engine
  12. }
  13. // Register registers a view engine.
  14. func (v *View) Register(e Engine) {
  15. v.engines = append(v.engines, e)
  16. }
  17. // Find receives a filename, gets its extension and returns the view engine responsible for that file extension
  18. func (v *View) Find(filename string) Engine {
  19. extension := filepath.Ext(filename)
  20. // Read-Only no locks needed, at serve/runtime-time the library is not supposed to add new view engines
  21. for i, n := 0, len(v.engines); i < n; i++ {
  22. e := v.engines[i]
  23. if e.Ext() == extension {
  24. return e
  25. }
  26. }
  27. return nil
  28. }
  29. // Len returns the length of view engines registered so far.
  30. func (v *View) Len() int {
  31. return len(v.engines)
  32. }
  33. var (
  34. errNoViewEngineForExt = errors.New("no view engine found for '%s'")
  35. )
  36. // ExecuteWriter calls the correct view Engine's ExecuteWriter func
  37. func (v *View) ExecuteWriter(w io.Writer, filename string, layout string, bindingData interface{}) error {
  38. if len(filename) > 2 {
  39. if filename[0] == '/' { // omit first slash
  40. filename = filename[1:]
  41. }
  42. }
  43. e := v.Find(filename)
  44. if e == nil {
  45. return errNoViewEngineForExt.Format(filepath.Ext(filename))
  46. }
  47. return e.ExecuteWriter(w, filename, layout, bindingData)
  48. }
  49. // AddFunc adds a function to all registered engines.
  50. // Each template engine that supports functions has its own AddFunc too.
  51. func (v *View) AddFunc(funcName string, funcBody interface{}) {
  52. for i, n := 0, len(v.engines); i < n; i++ {
  53. e := v.engines[i]
  54. if engineFuncer, ok := e.(EngineFuncer); ok {
  55. engineFuncer.AddFunc(funcName, funcBody)
  56. }
  57. }
  58. }
  59. // Load compiles all the registered engines.
  60. func (v *View) Load() error {
  61. for i, n := 0, len(v.engines); i < n; i++ {
  62. e := v.engines[i]
  63. if err := e.Load(); err != nil {
  64. return err
  65. }
  66. }
  67. return nil
  68. }