tpl.go 940 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package tpl
  2. import (
  3. "bytes"
  4. "html/template"
  5. "path/filepath"
  6. "strings"
  7. "git.clearsky.net.au/cody/gex.git/srv"
  8. "git.clearsky.net.au/cody/gex.git/utils"
  9. )
  10. type Props map[string]any
  11. type Funcs = template.FuncMap
  12. func include(req *srv.Req, props Props, funcs Funcs) {}
  13. var Include = include
  14. func Render(fp string, req *srv.Req, propFunc ...interface{}) string {
  15. if !strings.Contains(fp, "app/") {
  16. fp = utils.Cwd(2) + "/" + fp
  17. }
  18. fp = strings.Replace(fp, ".tpl", ".gen.tpl", 1)
  19. var props = Props{}
  20. var funcs = Funcs{}
  21. if len(propFunc) > 0 {
  22. props = propFunc[0].(Props)
  23. }
  24. if len(propFunc) > 1 {
  25. funcs = propFunc[1].(Funcs)
  26. }
  27. Include(req, props, funcs)
  28. tmpl, err := template.
  29. New(filepath.Base(fp)).
  30. Funcs(funcs).
  31. ParseFiles(fp)
  32. if err != nil {
  33. return err.Error()
  34. }
  35. var buf bytes.Buffer
  36. err = tmpl.Execute(&buf, props)
  37. if err != nil {
  38. return err.Error()
  39. }
  40. html := buf.String()
  41. return html
  42. }