~tsileo/blobstash

ref: ae2f65aeb1544cf14ee4c620886c23eff1f00631 blobstash/vendor/a4.io/gluapp/template.go -rw-r--r-- 2.2 KiB View raw
ae2f65aeThomas Sileo deps: update deps a month 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
84
85
86
87
88
89
90
91
package gluapp

import (
	"bytes"
	"fmt"
	"html/template"
	"path/filepath"
	"strings"
	"time"

	"a4.io/blobstash/pkg/apps/luautil"

	"github.com/yuin/goldmark"
	"github.com/yuin/goldmark/renderer/html"
	"github.com/yuin/gopher-lua"
)

var mdc = goldmark.New(
	goldmark.WithRendererOptions(
		html.WithHardWraps(),
		html.WithUnsafe(),
	),
)

var funcs = template.FuncMap{
	"markdownify": func(raw interface{}) template.HTML {
		var buf bytes.Buffer
		md := raw.(string)
		if err := mdc.Convert([]byte(strings.Replace(md, "\r\n", "\n", -1)), &buf); err != nil {
			panic(err)
		}
		return template.HTML(buf.String())
	},
	"htmlify": func(i string) template.HTML {
		return template.HTML(i)
	},
	"format_ts": func(ts float64, fmt string) string {
		return time.Unix(int64(ts), 0).Format(fmt)
	},
	"format": func(v interface{}, f string) string {
		return fmt.Sprintf(f, v)
	},
}

func setupTemplate(path string) func(*lua.LState) int {
	return func(L *lua.LState) int {
		// Setup the router module
		mod := L.SetFuncs(L.NewTable(), map[string]lua.LGFunction{
			"render_string": func(L *lua.LState) int {
				var out bytes.Buffer
				tpl, err := template.New("").Funcs(funcs).Parse(L.ToString(1))
				if err != nil {
					// TODO(tsileo): return error?
					return 0
				}
				if err := tpl.Execute(&out, luautil.TableToMap(L.ToTable(2))); err != nil {
					L.Push(lua.LString(err.Error()))
					return 1
				}
				L.Push(lua.LString(out.String()))
				return 1
			},
			"render": func(L *lua.LState) int {
				var out bytes.Buffer

				var templates []string
				for i := 1; i < L.GetTop(); i++ {
					// FIXME: remove dot in the filename
					templates = append(templates, filepath.Join(path, string(L.ToString(i))))
				}

				tmpl, err := template.New("").Funcs(funcs).ParseFiles(templates...)
				if err != nil {
					L.Push(lua.LString(err.Error()))
					return 1
				}
				tmplName := filepath.Base(templates[len(templates)-1])
				ctx := luautil.TableToMap(L.ToTable(L.GetTop()))
				if err := tmpl.ExecuteTemplate(&out, tmplName, ctx); err != nil {
					L.Push(lua.LString(err.Error()))
					return 1
				}

				L.Push(lua.LString(out.String()))
				return 1
			},
		})
		L.Push(mod)
		return 1
	}
}