render.go 931 B

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