package main import ( "io/ioutil" "os" pathpkg "path" "path/filepath" "strings" "text/template" ) // Templates contains site templates. type Templates struct { tmpls map[string]*template.Template funcs template.FuncMap } // NewTemplates returns a new Templates with the default templates. func NewTemplates() *Templates { t := &Templates{ tmpls: map[string]*template.Template{}, } return t } // Funcs sets the functions available to newly created templates. func (t *Templates) Funcs(funcs template.FuncMap) { t.funcs = funcs } // 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) } // LoadTemplate loads a template from the provided path and content. func (t *Templates) LoadTemplate(path string, content string) { tmpl := template.New(path) tmpl.Funcs(t.funcs) template.Must(tmpl.Parse(content)) t.tmpls[path] = tmpl } // Load loads templates from the provided directory func (t *Templates) Load(dir string) error { return filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { if err != nil { return err } if info.Mode().IsRegular() { b, err := ioutil.ReadFile(path) if err != nil { return err } // Remove directory from beginning of path path = strings.TrimPrefix(path, dir) t.LoadTemplate(path, string(b)) } return nil }) } // FindTemplate returns a template for the given path, or the default template if it does not exist. func (t *Templates) FindTemplate(path string, tmpl string) *template.Template { tmplPath := pathpkg.Join(path, tmpl) if t, ok := t.tmpls[tmplPath]; ok { return t } return t.tmpls[pathpkg.Join("/_default", tmpl)] } // Default index template const index_gmi = `# {{ .Title }} {{ if .Content }} {{ .Content }}{{ end }} {{ if .Dirs }}{{ range .Dirs }}=> {{ .Path }}{{ if .Title }} {{ .Title }}{{ end }} {{ end }} {{ 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" }} {{- if site.Title }} on {{ site.Title }}{{ end }}{{ end }} {{ .Content }}` // Default template for html output const output_html = ` {{ .Title }} {{ .Content }}` // Default atom feed template const atom_xml = ` {{ site.URL }}{{ .Path }} {{ .Title }} {{ .Updated.Format "2006-01-02T15:04:05Z07:00" }} {{ range .Entries }} {{ site.URL }}{{ .Path }} {{ .Title }} {{ .Date.Format "2006-01-02T15:04:05Z07:00" }} {{ end -}} `