forked from harness/gitness
-
Notifications
You must be signed in to change notification settings - Fork 0
/
template.go
95 lines (85 loc) · 1.74 KB
/
template.go
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
92
93
94
95
package web
import (
"bytes"
"encoding/json"
"fmt"
"html/template"
"strings"
"golang.org/x/net/html"
)
// default func map with json parser.
var funcMap = template.FuncMap{
"json": func(v interface{}) template.JS {
a, _ := json.Marshal(v)
return template.JS(a)
},
}
// helper function creates a new template from the text string.
func mustCreateTemplate(text string) *template.Template {
templ, err := createTemplate(text)
if err != nil {
panic(err)
}
return templ
}
// helper function creates a new template from the text string.
func createTemplate(text string) (*template.Template, error) {
templ, err := template.New("_").Funcs(funcMap).Parse(partials)
if err != nil {
return nil, err
}
return templ.Parse(
injectPartials(text),
)
}
// helper function that parses the html file and injects
// named partial templates.
func injectPartials(s string) string {
w := new(bytes.Buffer)
r := bytes.NewBufferString(s)
t := html.NewTokenizer(r)
for {
tt := t.Next()
if tt == html.ErrorToken {
break
}
if tt == html.CommentToken {
txt := string(t.Text())
txt = strings.TrimSpace(txt)
seg := strings.Split(txt, ":")
if len(seg) == 2 && seg[0] == "drone" {
fmt.Fprintf(w, "{{ template %q . }}", seg[1])
continue
}
}
w.Write(t.Raw())
}
return w.String()
}
const partials = `
{{define "user"}}
{{ if .user }}
<script>
window.DRONE_USER = {{ json .user }};
window.DRONE_SYNC = {{ .syncing }};
</script>
{{ end }}
{{end}}
{{define "csrf"}}
{{ if .csrf -}}
<script>
window.DRONE_CSRF = "{{ .csrf }}"
</script>
{{- end }}
{{end}}
{{define "version"}}
<meta name="version" content="{{ .version }}">
{{end}}
{{define "docs"}}
{{ if .docs -}}
<script>
window.DRONE_DOCS = "{{ .docs }}"
</script>
{{- end }}
{{end}}
`