8356
Wx
www-xonecas-io / files
www-xonecas-io / internal / site / render.go
1.6 KB
1// Package site renders the pages of xonecas.io from repositories. The server picks the page and writes it. 2package site 3 4import ( 5 "embed" 6 "errors" 7 "html/template" 8 "io" 9 "strconv" 10 "strings" 11) 12 13//go:embed templates/*.html 14var templates embed.FS 15 16//go:embed static 17var static embed.FS 18 19// ErrNotFound is a page that does not exist: an unknown project, path, commit or page number. 20var ErrNotFound = errors.New("not found") 21 22var funcs = template.FuncMap{ 23 "list": func(v ...any) []any { return v }, 24 "lower": strings.ToLower, 25 "comma": func(n int) string { 26 s := strconv.Itoa(n) 27 for i := len(s) - 3; i > 0; i -= 3 { 28 s = s[:i] + "," + s[i:] 29 } 30 return s 31 }, 32 "asset": asset, 33 "inc": func(i int) int { return i + 1 }, 34 "maxDiff": func() int { return MaxDiffLines }, 35 "dec": func(i int) int { return i - 1 }, 36 "web": func(url string) string { // "" for a repo with no other home: hosted here, or local 37 if !strings.HasPrefix(url, "https://") || strings.HasPrefix(url, BaseURL+"/") { 38 return "" 39 } 40 return strings.TrimSuffix(strings.TrimPrefix(url, "https://"), ".git") 41 }, 42 "dict": func(kv ...any) (map[string]any, error) { 43 if len(kv)%2 != 0 { 44 return nil, errors.New("dict needs key, value pairs") 45 } 46 m := map[string]any{} 47 for i := 0; i < len(kv); i += 2 { 48 m[kv[i].(string)] = kv[i+1] 49 } 50 return m, nil 51 }, 52} 53 54var pages = template.Must(template.New("").Funcs(funcs).ParseFS(templates, "templates/*.html")) 55 56// Render writes the template name, a page such as "projects.html" or a fragment such as "suggest", with data. 57func Render(w io.Writer, name string, data any) error { 58 return pages.ExecuteTemplate(w, name, data) 59}