From 04d59927ab92b49fbe8e94d2cf357eee91ad058c Mon Sep 17 00:00:00 2001 From: Timur Ismagilov Date: Mon, 3 Jun 2024 22:27:26 +0300 Subject: [PATCH] Implement yet another template system --- newtmpl/base.html | 56 ++++++++++++++++++++++++++++++++++++++++++++++ newtmpl/newtmpl.go | 54 ++++++++++++++++++++++++++++++++++++++++++++ viewutil/meta.go | 8 +++++++ 3 files changed, 118 insertions(+) create mode 100644 newtmpl/base.html create mode 100644 newtmpl/newtmpl.go diff --git a/newtmpl/base.html b/newtmpl/base.html new file mode 100644 index 0000000..48ac707 --- /dev/null +++ b/newtmpl/base.html @@ -0,0 +1,56 @@ +{{define "confirm"}}Confirm{{end}} +{{define "cancel"}}Cancel{{end}} +{{define "save"}}Save{{end}} +{{define "error"}}Error{{end}} +{{define "delete"}}Delete{{end}} +{{define "page"}} + + + + + + {{block "title" .}}{{end}} + + + {{range .HeadElements}}{{.}}{{end}} + + +
+ +
+{{block "body" .}}{{end}} + + + +{{range .CommonScripts}} + +{{end}} + + +{{end}} diff --git a/newtmpl/newtmpl.go b/newtmpl/newtmpl.go new file mode 100644 index 0000000..1f0ce1a --- /dev/null +++ b/newtmpl/newtmpl.go @@ -0,0 +1,54 @@ +package newtmpl + +import ( + "embed" + "fmt" + "github.com/bouncepaw/mycorrhiza/cfg" + "html/template" + "strings" + + "github.com/bouncepaw/mycorrhiza/viewutil" +) + +//go:embed *.html +var fs embed.FS + +type Page struct { + TemplateEnglish *template.Template + TemplateRussian *template.Template +} + +func NewPage(tmpl string, russianTranslation map[string]string) *Page { + must := template.Must + + return &Page{ + TemplateEnglish: must(template.ParseFS(fs, "base.html")), + TemplateRussian: must(must(template.ParseFS(fs, "base.html")). + Parse(translationsIntoTemplates(russianTranslation))), + } +} + +func translationsIntoTemplates(m map[string]string) string { + var sb strings.Builder + for k, v := range m { + sb.WriteString(fmt.Sprintf(`{{define "%s"}}%s{{end}} +`, k, v)) + } + return sb.String() +} + +func (p *Page) RenderTo(meta viewutil.Meta, data map[string]any) error { + data["Meta"] = meta + data["HeadElements"] = meta.HeadElements + data["BodyAttributes"] = meta.BodyAttributes + data["CommonScripts"] = cfg.CommonScripts + data["EditScripts"] = cfg.EditScripts + data["HeaderLinks"] = viewutil.HeaderLinks + + tmpl := p.TemplateEnglish + if meta.LocaleIsRussian() { + tmpl = p.TemplateRussian + } + + return tmpl.ExecuteTemplate(meta.W, "page", data) +} diff --git a/viewutil/meta.go b/viewutil/meta.go index d69b35f..4c2c05d 100644 --- a/viewutil/meta.go +++ b/viewutil/meta.go @@ -13,6 +13,10 @@ type Meta struct { U *user.User W io.Writer Addr string + + // New template additions + HeadElements []string + BodyAttributes map[string]string } // MetaFrom makes a Meta from the given data. You are meant to further modify it. @@ -28,3 +32,7 @@ func MetaFrom(w http.ResponseWriter, rq *http.Request) Meta { func (m Meta) Locale() string { return m.Lc.Locale } + +func (m Meta) LocaleIsRussian() bool { + return m.Locale() == "ru" +}