~evanj/evanjon.es

ref: b2569bb225045d9d1d9f58c51dbc8cb5a9f79f58 evanjon.es/internal/s/tmpl/tmpl.go -rw-r--r-- 1.8 KiB
b2569bb2Evan J Feat(go1.16, embed, Nu Html Checker): Fixing HTML issues as reported by 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package tmpl

import (
	"embed"
	"html/template"
	"log"
	"path/filepath"
	"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:embed */*
var templs embed.FS

var all = template.Must(
	template.New("").
		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
			},
		})).
		ParseFS(templs, "*/*"))

// init will minimize all css, html, and javascript assets.
func init() {
	minifier := minify.New()
	minifier.AddFunc("text/css", css.Minify)
	minifier.AddFunc("text/html", html.Minify)
	minifier.AddFunc("application/javascript", js.Minify)

	var minimize func(dirname string)
	minimize = func(dirname string) {
		dir, err := templs.ReadDir(dirname)
		if err != nil {
			log.Fatal(err)
		}

		for _, entry := range dir {
			if entry.IsDir() {
				minimize(filepath.Join(dirname, entry.Name()))
				continue
			}

			name := filepath.Join(dirname, entry.Name())
			bytes, err := templs.ReadFile(name)
			if err != nil {
				log.Fatal(err)
			}

			switch filepath.Ext(name) {
			case ".html":
				bytes, err = minifier.Bytes("text/html", bytes)
				break
			case ".css":
				bytes, err = minifier.Bytes("text/css", bytes)
				break
			case ".js":
				bytes, err = minifier.Bytes("application/javascript", bytes)
				break
			}

			all = template.Must(all.New(name).Parse(string(bytes)))
		}
	}

	minimize("img")
	minimize("css")
	minimize("html")
}

func MustParse(name string) *template.Template {
	t := all.Lookup(name)
	if t == nil {
		log.Fatalf("template %s does not exist", name)
	}
	return t
}