mirror of
https://github.com/nkanaev/yarr.git
synced 2026-07-15 11:06:31 +00:00
frontend: simplify assets filesystem
This commit is contained in:
@@ -1,61 +1,19 @@
|
||||
//go:build debug
|
||||
|
||||
package assets
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"html/template"
|
||||
"io"
|
||||
"io/fs"
|
||||
"log"
|
||||
"os"
|
||||
)
|
||||
|
||||
type assetsfs struct {
|
||||
embedded *embed.FS
|
||||
templates map[string]*template.Template
|
||||
const rootDir = "src/assets"
|
||||
|
||||
func Templates() *template.Template {
|
||||
return template.Must(template.ParseGlob(rootDir + "/templates/*.html"))
|
||||
}
|
||||
|
||||
var FS assetsfs
|
||||
|
||||
func (afs assetsfs) Open(name string) (fs.File, error) {
|
||||
if afs.embedded != nil {
|
||||
return afs.embedded.Open(name)
|
||||
}
|
||||
return os.DirFS("src/assets").Open(name)
|
||||
}
|
||||
|
||||
func Template(path string) *template.Template {
|
||||
var tmpl *template.Template
|
||||
tmpl, found := FS.templates[path]
|
||||
if !found {
|
||||
tmpl = template.Must(template.New(path).Delims("{%", "%}").Funcs(template.FuncMap{
|
||||
"inline": func(svg string) template.HTML {
|
||||
svgfile, err := FS.Open("graphicarts/" + svg)
|
||||
// should never happen
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer svgfile.Close()
|
||||
|
||||
content, err := io.ReadAll(svgfile)
|
||||
// should never happen
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
return template.HTML(content)
|
||||
},
|
||||
}).ParseFS(FS, path))
|
||||
if FS.embedded != nil {
|
||||
FS.templates[path] = tmpl
|
||||
}
|
||||
}
|
||||
return tmpl
|
||||
}
|
||||
|
||||
func Render(path string, writer io.Writer, data any) {
|
||||
tmpl := Template(path)
|
||||
tmpl.Execute(writer, data)
|
||||
}
|
||||
|
||||
func init() {
|
||||
FS.templates = make(map[string]*template.Template)
|
||||
func StaticFS() fs.FS {
|
||||
return os.DirFS(rootDir)
|
||||
}
|
||||
|
||||
@@ -2,14 +2,24 @@
|
||||
|
||||
package assets
|
||||
|
||||
import "embed"
|
||||
import (
|
||||
"embed"
|
||||
"html/template"
|
||||
"io/fs"
|
||||
)
|
||||
|
||||
//go:embed *.html
|
||||
//go:embed graphicarts
|
||||
//go:embed javascripts
|
||||
//go:embed stylesheets
|
||||
var embedded embed.FS
|
||||
var static embed.FS
|
||||
|
||||
func init() {
|
||||
FS.embedded = &embedded
|
||||
//go:embed templates
|
||||
var templates embed.FS
|
||||
|
||||
func Templates() *template.Template {
|
||||
return template.Must(template.ParseFS(templates, "*.html"))
|
||||
}
|
||||
|
||||
func StaticFS() fs.FS {
|
||||
return static
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user