Optimize template parsing

This commit is contained in:
Jan-Lukas Else 2021-03-11 09:16:19 +01:00
parent 5e65fd6bd7
commit 0a4d552cd1
3 changed files with 20 additions and 16 deletions

View File

@ -41,11 +41,10 @@ const (
templateWebmentionAdmin = "webmentionadmin"
)
var templates map[string]*template.Template
var templateFunctions template.FuncMap
var templates map[string]*template.Template = map[string]*template.Template{}
func initRendering() error {
templateFunctions = template.FuncMap{
templateFunctions := template.FuncMap{
"menu": func(blog *configBlog, id string) *menu {
return blog.Menus[id]
},
@ -169,22 +168,24 @@ func initRendering() error {
},
}
templates = map[string]*template.Template{}
baseTemplatePath := path.Join(templatesDir, templateBase+templatesExt)
if err := filepath.Walk(templatesDir, func(p string, info os.FileInfo, err error) error {
baseTemplate, err := template.New("base").Funcs(templateFunctions).ParseFiles(path.Join(templatesDir, templateBase+templatesExt))
if err != nil {
return err
}
err = filepath.Walk(templatesDir, func(p string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.Mode().IsRegular() && path.Ext(p) == templatesExt {
if name := strings.TrimSuffix(path.Base(p), templatesExt); name != templateBase {
if templates[name], err = template.New(name).Funcs(templateFunctions).ParseFiles(baseTemplatePath, p); err != nil {
if templates[name], err = template.Must(baseTemplate.Clone()).New(name).ParseFiles(p); err != nil {
return err
}
}
}
return nil
}); err != nil {
})
if err != nil {
return err
}
return nil

View File

@ -5,7 +5,9 @@
<meta name=viewport content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="{{ asset "css/styles.css" }}">
{{ with .Canonical }}<link rel="canonical" href="{{ . }}">{{ end }}
{{ template "title" . }}
{{ block "title" . }}
<title>{{ .Blog.Title }}</title>
{{ end }}
<link rel="alternate" type="application/rss+xml" title="RSS ({{ .Blog.Title }})" href="{{ .Blog.Path }}.rss"/>
<link rel="alternate" type="application/atom+xml" title="Atom ({{ .Blog.Title }})" href="{{ .Blog.Path }}.atom"/>
<link rel="alternate" type="application/feed+json" title="JSON Feed ({{ .Blog.Title }})" href="{{ .Blog.Path }}.json"/>
@ -19,7 +21,7 @@
{{ end }}
{{ end }}
{{ include "header" . }}
{{ template "main" . }}
{{ block "main" . }}{{ end }}
{{ include "footer" . }}
</html>
{{ end }}

View File

@ -34,14 +34,15 @@ func sortedStrings(s []string) []string {
return s
}
const randomLetters = "abcdefghijklmnopqrstuvwxyz"
func generateRandomString(chars int) string {
rand.Seed(time.Now().UnixNano())
letters := []rune("abcdefghijklmnopqrstuvwxyz")
b := make([]rune, chars)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
var b strings.Builder
for i := 0; i < chars; i++ {
b.WriteByte(randomLetters[rand.Intn(len(randomLetters))])
}
return string(b)
return b.String()
}
func isAllowedHost(r *http.Request, hosts ...string) bool {