~nromdotcom/gemif

ref: acbff041b42d9775f953097bc874de05295b1c85 gemif/pkg/gemserver/template.go -rw-r--r-- 1.1 KiB
acbff041Norm MacLennan Add configuration 1 year, 8 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package gemserver

import (
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"text/template"

	"github.com/markbates/pkger"
	"github.com/pitr/gig"
)

// Template contains the templates for gig to render.
type Template struct {
	templates *template.Template
}

// Render is a simple rendering function for our text/template to Gemini for gig.
func (t *Template) Render(w io.Writer, name string, data interface{}, c gig.Context) error {
	return t.templates.ExecuteTemplate(w, name, data)
}

func compileTemplates() (*template.Template, error) {
	var files []string

	var tmpl *template.Template

	err := pkger.Walk("/static/templates", func(path string, info os.FileInfo, err error) error {
		if info.IsDir() {
			return nil
		}
		files = append(files, path)

		return nil
	})
	if err != nil {
		return tmpl, fmt.Errorf("couldn't compile template %w", err)
	}

	tempTmpl := template.New("")

	for _, file := range files {
		f, _ := pkger.Open(file)
		sl, _ := ioutil.ReadAll(f)

		template.Must(tempTmpl.New(file).Parse(string(sl)))

		if err != nil {
			fmt.Printf("unable to compile template %s", err)
			os.Exit(1)
		}
	}

	tmpl = tempTmpl

	return tmpl, nil
}