pug.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package view
  2. import (
  3. "bytes"
  4. "io/ioutil"
  5. "path"
  6. "strings"
  7. "github.com/iris-contrib/jade"
  8. )
  9. // Pug (or Jade) returns a new pug view engine.
  10. // It shares the same exactly logic with the
  11. // html view engine, it uses the same exactly configuration.
  12. // The given "extension" MUST begin with a dot.
  13. //
  14. // Read more about the Jade Go Parser: https://github.com/Joker/jade
  15. //
  16. // Examples:
  17. // https://github.com/kataras/iris/tree/master/_examples/view/template_pug_0
  18. // https://github.com/kataras/iris/tree/master/_examples/view/template_pug_1
  19. // https://github.com/kataras/iris/tree/master/_examples/view/template_pug_2
  20. // https://github.com/kataras/iris/tree/master/_examples/view/template_pug_3
  21. func Pug(directory, extension string) *HTMLEngine {
  22. s := HTML(directory, extension)
  23. s.middleware = func(name string, text []byte) (contents string, err error) {
  24. name = path.Join(path.Clean(directory), name)
  25. tmpl := jade.New(name)
  26. tmpl.ReadFunc = func(name string) ([]byte, error) {
  27. if !strings.HasPrefix(path.Clean(name), path.Clean(directory)) {
  28. name = path.Join(directory, name)
  29. }
  30. if s.assetFn != nil {
  31. return s.assetFn(name)
  32. }
  33. return ioutil.ReadFile(name)
  34. }
  35. // Fixes: https://github.com/kataras/iris/issues/1450
  36. // by adding a custom ReadFunc inside the jade parser.
  37. // And Also able to use relative paths on "extends" and "include" directives:
  38. // e.g. instead of extends "templates/layout.pug" we use "layout.pug"
  39. // so contents of templates are independent of their root location.
  40. exec, err := tmpl.Parse(text)
  41. if err != nil {
  42. return
  43. }
  44. b := new(bytes.Buffer)
  45. exec.WriteIn(b)
  46. return b.String(), nil
  47. }
  48. return s
  49. }