Implement function that resolves mapping between content and template

pull/1/head
Nikita Tokarchuk 3 years ago
parent 1d970ddcd7
commit 156c3fd2cc
Signed by: mainnika
GPG Key ID: A595FB7E3E56911C
  1. 33
      frontend/templates/templates.go

@ -3,8 +3,10 @@ package templates
import ( import (
"bytes" "bytes"
"embed" "embed"
"fmt"
"html/template" "html/template"
"io/fs" "io/fs"
"reflect"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
@ -52,3 +54,34 @@ func init() {
logrus.Debugf("Templates loading complete%s", Templates.DefinedTemplates()) logrus.Debugf("Templates loading complete%s", Templates.DefinedTemplates())
} }
// MustLookup wraps lookup function for the root template namespace
func MustLookup(name string) *template.Template {
tmpl := Templates.Lookup(name)
if tmpl == nil {
panic(fmt.Errorf("cannot find template %s", name))
}
return tmpl
}
// GetTemplateOf returns template which is mapped to the content data
func GetTemplateOf(content interface{}) (template *template.Template) {
el := reflect.TypeOf(content)
numField := el.NumField()
for i := 0; i < numField; i++ {
field := el.Field(i)
tag := field.Tag
found, ok := tag.Lookup("template")
if !ok {
continue
}
return MustLookup(found)
}
panic(fmt.Errorf("content %v does not have a template tag", content))
}

Loading…
Cancel
Save