~evanj/evanjon.es

ref: 3d3bf1d95ab2d9409b24eccba85b8f8d46b159ee evanjon.es/internal/s/tmpl/tmpl.go -rw-r--r-- 1.3 KiB
3d3bf1d9Evan J Feat(vendor): Vendor updates for go1.16. 11 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
59
60
61
package tmpl

import (
	"html/template"
	"path/filepath"
	"sync"
	"time"

	"github.com/tdewolff/minify/v2"
	"github.com/tdewolff/minify/v2/css"
	"github.com/tdewolff/minify/v2/html"
	"github.com/tdewolff/minify/v2/js"
)

//go:generate embed -pattern */* -id tmpls

var (
	all = template.New("cms").
		Funcs(template.FuncMap(map[string]interface{}{
			"html": func(val string) template.HTML { return template.HTML(val) },
			"date": func(val string) (string, error) {
				date, err := time.Parse("2006-01-02", val)
				return date.Format("Jan 2, 2006"), err
			},
		}))
	minifier = minify.New()
	once     sync.Once
)

func MustParse(name string) *template.Template {
	once.Do(func() {
		minifier.AddFunc("text/css", css.Minify)
		minifier.AddFunc("text/html", html.Minify)
		minifier.AddFunc("application/javascript", js.Minify)

		for key, val := range tmpls {
			var err error
			ext := filepath.Ext(key)

			switch ext {
			case ".html":
				val, err = minifier.String("text/html", val)
				break
			case ".css":
				val, err = minifier.String("text/css", val)
				break
			case ".js":
				val, err = minifier.String("application/javascript", val)
				break
			}

			if err != nil {
				panic(err.Error())
			}

			all = template.Must(all.New(key).Parse(val))
		}
	})

	return all.Lookup(name)
}