about summary refs log tree commit diff stats
path: root/internal/server/templates.go
blob: 0b397292e1de508fd351606b7db03aa22c627361 (plain)
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
package server

import (
	"fmt"
	"html"
	"html/template"
	"log/slog"
	"os"
	"path"
	"path/filepath"
	"searchix/internal/options"
	"strings"

	"github.com/pkg/errors"
	"github.com/yuin/goldmark"
	"github.com/yuin/goldmark/extension"
)

type TemplateCollection map[string]*template.Template

var md = goldmark.New(
	goldmark.WithExtensions(extension.NewLinkify()),
)
var templateFuncs = template.FuncMap{
	"markdown": func(input options.Markdown) template.HTML {
		var out strings.Builder
		err := md.Convert([]byte(input), &out)
		if err != nil {
			slog.Warn(fmt.Sprintf("markdown conversion failed: %v", err))

			return template.HTML(html.EscapeString(err.Error())) // #nosec G203 -- duh?
		}

		return template.HTML(out.String()) // #nosec G203
	},
}

func loadTemplate(filename string) (*template.Template, error) {
	text, err := os.ReadFile(filename)
	if err != nil {
		return nil, errors.WithMessage(err, "could not read template")
	}
	name, _ := strings.CutSuffix(path.Base(filename), ".gotmpl")
	tpl := template.New(name)
	tpl.Funcs(templateFuncs)
	_, err = tpl.Parse(string(text))
	if err != nil {
		return nil, errors.WithMessage(err, "could not parse template")
	}

	return tpl, nil
}

func loadTemplates() (TemplateCollection, error) {
	templateDir := path.Join("frontend", "templates")
	templates := make(TemplateCollection, 0)

	index, err := loadTemplate(path.Join(templateDir, "index.gotmpl"))
	if err != nil {
		return nil, err
	}
	templates["index"] = index

	templatePaths, err := filepath.Glob(path.Join(templateDir, "blocks", "*.gotmpl"))
	if err != nil {
		return nil, errors.WithMessage(err, "could not glob block templates")
	}
	for _, fullname := range templatePaths {
		tpl, err := loadTemplate(fullname)
		if err != nil {
			return nil, err
		}
		_, err = tpl.AddParseTree("index", index.Tree)
		if err != nil {
			return nil, errors.WithMessage(err, "could not add index template")
		}
		templates[tpl.Name()] = tpl
	}

	return templates, nil
}