From d565d4b8c86c3e7e9c84f42bb89ef87b7e8f732e Mon Sep 17 00:00:00 2001 From: Adnan Maolood Date: Sat, 27 Feb 2021 15:56:23 -0500 Subject: [PATCH] Embed built-in templates with embed.FS --- templates.go | 68 +++++++++++++++------------------------------------- 1 file changed, 19 insertions(+), 49 deletions(-) diff --git a/templates.go b/templates.go index 20b6254..c86a7b4 100644 --- a/templates.go +++ b/templates.go @@ -1,6 +1,7 @@ package main import ( + "embed" "io/ioutil" "os" pathpkg "path" @@ -9,6 +10,9 @@ import ( "text/template" ) +//go:embed templates +var builtinTemplates embed.FS + // Templates contains site templates. type Templates struct { tmpls map[string]*template.Template @@ -31,17 +35,25 @@ func (t *Templates) Funcs(funcs template.FuncMap) { // LoadDefault loads the default templates. // Should be called after Funcs. func (t *Templates) LoadDefault() { - t.LoadTemplate("/_default/index.gmi", index_gmi) - t.LoadTemplate("/_default/page.gmi", page_gmi) - t.LoadTemplate("/_default/atom.xml", atom_xml) - t.LoadTemplate("/_default/output.html", output_html) + t.loadDefault("index.gmi") + t.loadDefault("page.gmi") + t.loadDefault("atom.xml") + t.loadDefault("output.html") +} + +func (t *Templates) loadDefault(name string) { + b, err := builtinTemplates.ReadFile("templates/" + name) + if err != nil { + panic(err) + } + t.LoadTemplate("/_default/"+name, b) } // LoadTemplate loads a template from the provided path and content. -func (t *Templates) LoadTemplate(path string, content string) { +func (t *Templates) LoadTemplate(path string, content []byte) { tmpl := template.New(path) tmpl.Funcs(t.funcs) - template.Must(tmpl.Parse(content)) + template.Must(tmpl.Parse(string(content))) t.tmpls[path] = tmpl } @@ -58,7 +70,7 @@ func (t *Templates) Load(dir string) error { } // Remove directory from beginning of path path = strings.TrimPrefix(path, dir) - t.LoadTemplate(path, string(b)) + t.LoadTemplate(path, b) } return nil }) @@ -72,45 +84,3 @@ func (t *Templates) FindTemplate(path string, tmpl string) *template.Template { } return t.tmpls[pathpkg.Join("/_default", tmpl)] } - -// Default index template -const index_gmi = `# {{ .Title }} -{{ if .Content }} -{{ .Content }}{{ end }} -{{ range .Pages }}=> {{ .Path }} {{ if not .Date.IsZero -}} -{{.Date.Format "2006-01-02"}} {{end}}{{.Title}} -{{ end -}}` - -// Default page template -const page_gmi = `# {{ .Title }} -{{- if not .Date.IsZero }} -Posted on {{ .Date.Format "2006-01-02" }}{{ end }} - -{{ .Content }}` - -// Default template for html output -const output_html = ` - - -{{ .Title }} - -{{ .Content }}` - -// Default atom feed template -const atom_xml = ` - -{{ index site.URLs 0 }}{{ .Path }} -{{ .Title }} -{{ .Updated.Format "2006-01-02T15:04:05Z07:00" }} - -{{ range .Entries }} - {{ index site.URLs 0 }}{{ .Path }} - {{ .Title }} - {{ .Date.Format "2006-01-02T15:04:05Z07:00" }} - {{- $path := .Path }} - {{- range site.URLs }} - - {{- end }} - -{{ end -}} -`