render.go 813 B

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