budget-go/backend/view/view.go
2025-02-08 20:19:26 +01:00

87 lines
1.6 KiB
Go

package view
import (
"embed"
"encoding/json"
"fmt"
"strings"
"github.com/a-h/templ"
"github.com/labstack/echo/v4"
)
var (
//go:embed static/*
statics embed.FS
manifest map[string]string
entrypoints map[string]map[string]map[string][]string
)
func Render(ctx echo.Context, statusCode int, t templ.Component) error {
buf := templ.GetBuffer()
defer templ.ReleaseBuffer(buf)
if err := t.Render(ctx.Request().Context(), buf); err != nil {
return err
}
return ctx.HTML(statusCode, buf.String())
}
func Asset(name string) string {
if manifest == nil {
value, _ := statics.ReadFile("static/manifest.json")
json.Unmarshal(value, &manifest)
}
path, ok := manifest[name]
if !ok {
return ""
}
return path
}
func entrypointFiles(app, category string) []string {
if entrypoints == nil {
value, _ := statics.ReadFile("static/entrypoints.json")
json.Unmarshal(value, &entrypoints)
}
entry, ok := entrypoints["entrypoints"][app]
if !ok {
return []string{}
}
files, ok := entry[category]
if !ok {
return []string{}
}
return files
}
func EntrypointJs(app string) string {
files := entrypointFiles(app, "js")
results := []string{}
for _, file := range files {
results = append(results, fmt.Sprintf(`<script src="%s"></script>`, file))
}
return strings.Join(results, "")
}
func EntrypointCss(app string) string {
files := entrypointFiles(app, "css")
results := []string{}
for _, file := range files {
results = append(results, fmt.Sprintf(`<link rel="stylesheet" href="%s" />`, file))
}
return strings.Join(results, "")
}