1
0
mirror of https://github.com/osmarks/mycorrhiza.git synced 2024-10-30 03:36:16 +00:00
mycorrhiza/viewutil/viewutil.go

98 lines
2.3 KiB
Go
Raw Normal View History

2022-03-29 20:59:36 +00:00
// Package viewutil provides utilities and common templates for views across all packages.
package viewutil
import (
"embed"
"fmt"
"github.com/bouncepaw/mycorrhiza/cfg"
"github.com/bouncepaw/mycorrhiza/util"
2022-04-02 07:10:32 +00:00
"io/fs"
2022-03-29 20:59:36 +00:00
"log"
"strings"
"text/template" // TODO: save the world
2022-03-29 20:59:36 +00:00
)
var (
//go:embed *.html
2022-04-02 07:10:32 +00:00
fsys embed.FS
2022-03-29 20:59:36 +00:00
BaseEn *template.Template
BaseRu *template.Template
m = template.Must
)
const ruText = `
{{define "search by title"}}Поиск по названию{{end}}
{{define "close this dialog"}}Закрыть этот диалог{{end}}
{{define "login"}}Войти{{end}}
2022-04-21 14:32:58 +00:00
{{define "register"}}Регистрация{{end}}
2022-03-29 20:59:36 +00:00
`
func Init() {
dataText := fmt.Sprintf(`
{{define "wiki name"}}%s{{end}}
2022-04-21 14:32:58 +00:00
{{define "user hypha"}}%s{{end}}
`, cfg.WikiName, cfg.UserHypha)
BaseEn = m(m(template.New("").
Funcs(template.FuncMap{
"beautifulName": util.BeautifulName,
2022-04-02 07:10:32 +00:00
}).ParseFS(fsys, "base.html")).
Parse(dataText))
2022-03-29 20:59:36 +00:00
if !cfg.UseAuth {
m(BaseEn.Parse(`{{define "auth"}}{{end}}`))
}
if !cfg.AllowRegistration {
m(BaseEn.Parse(`{{define "registration"}}{{end}}`))
}
BaseRu = m(m(BaseEn.Clone()).Parse(ruText))
}
// TODO: get rid of this
func localizedBaseWithWeirdBody(meta Meta) *template.Template {
t := func() *template.Template {
if meta.Locale() == "ru" {
return BaseRu
}
return BaseEn
}()
return m(m(t.Clone()).Parse(`
{{define "body"}}{{.Body}}{{end}}
{{define "title"}}{{.Title}}{{end}}
`))
2022-03-29 20:59:36 +00:00
}
type BaseData struct {
2022-03-29 20:59:36 +00:00
Meta Meta
HeadElements []string
HeaderLinks []cfg.HeaderLink
CommonScripts []string
Title string // TODO: remove
2022-03-29 20:59:36 +00:00
Body string // TODO: remove
}
// Base is a temporary wrapper around BaseEn and BaseRu, meant to facilitate the migration from qtpl.
2022-04-01 19:51:15 +00:00
func Base(meta Meta, title, body string, headElements ...string) string {
2022-03-29 20:59:36 +00:00
var w strings.Builder
2022-04-01 19:51:15 +00:00
meta.W = &w
2022-03-29 20:59:36 +00:00
t := localizedBaseWithWeirdBody(meta)
err := t.ExecuteTemplate(&w, "page", BaseData{
2022-03-29 20:59:36 +00:00
Meta: meta,
Title: title,
HeadElements: headElements,
HeaderLinks: cfg.HeaderLinks,
CommonScripts: cfg.CommonScripts,
Body: body,
})
if err != nil {
log.Println(err)
}
return w.String()
}
2022-04-02 07:10:32 +00:00
func CopyEnWith(fsys fs.FS, f string) *template.Template {
return m(m(BaseEn.Clone()).ParseFS(fsys, f))
}
func CopyRuWith(fsys fs.FS, f string) *template.Template {
return m(m(BaseRu.Clone()).ParseFS(fsys, f))
}