templates.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package fiber
  2. import (
  3. "errors"
  4. "git.dmitriygnatenko.ru/dima/go-common/logger"
  5. "github.com/gofiber/fiber/v2"
  6. "github.com/gofiber/template/html/v2"
  7. customErrors "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/helper/errors"
  8. "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/service/i18n"
  9. "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/template/functions"
  10. )
  11. func getViewsEngine(sp ServiceProvider) *html.Engine {
  12. engine := html.New(sp.ConfigService().AppTemplatesPath(), ".html")
  13. engine.AddFunc("now", functions.Now)
  14. engine.AddFunc("noescape", functions.NoEscape)
  15. engine.AddFunc("concat", functions.Concat)
  16. engine.AddFunc("gridsep", functions.GridSep)
  17. engine.AddFunc("version", functions.Version(sp))
  18. engine.AddFunc("trans", functions.Trans)
  19. engine.AddFunc("link", functions.Link)
  20. return engine
  21. }
  22. func getErrorHandler() fiber.ErrorHandler {
  23. return func(fctx *fiber.Ctx, err error) error {
  24. lang := i18n.LanguageFromContext(fctx)
  25. errCode := fiber.StatusInternalServerError
  26. var e *fiber.Error
  27. if errors.As(err, &e) {
  28. errCode = e.Code
  29. }
  30. renderData := fiber.Map{
  31. "lang": lang,
  32. "headTitle": i18n.T(lang, "head_title"),
  33. }
  34. if errCode == fiber.StatusNotFound {
  35. renderData["pageTitle"] = i18n.T(lang, "page_not_found_err_title")
  36. renderData["code"] = fiber.StatusNotFound
  37. renderData["text"] = i18n.T(lang, "page_not_found_err_desc")
  38. } else {
  39. renderData["pageTitle"] = i18n.T(lang, "internal_err_title")
  40. renderData["code"] = fiber.StatusInternalServerError
  41. renderData["text"] = i18n.T(lang, "internal_err_desc")
  42. }
  43. if err = fctx.Render("error", renderData, "_layout"); err != nil {
  44. logger.Error(fctx.Context(), customErrors.Wrap(err, "render error template").Error())
  45. }
  46. return nil
  47. }
  48. }