/
template.go
214 lines (174 loc) · 7.07 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
// Copyright 2018 SHIFT72
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package models
import (
"bytes"
"fmt"
"reflect"
"regexp"
"strings"
"github.com/CloudyKit/jet"
"github.com/indiereign/shift72-kibble/kibble/version"
"github.com/microcosm-cc/bluemonday"
"github.com/nicksnyder/go-i18n/i18n"
"github.com/russross/blackfriday"
)
var templateTagRegex = regexp.MustCompile("(?U:{{.+}})+")
var shortCodeView *jet.Set
// CreateTemplateView - create a template view
func CreateTemplateView(routeRegistry *RouteRegistry, trans i18n.TranslateFunc, ctx *RenderContext, templatePath string) *jet.Set {
view := jet.NewHTMLSet(templatePath)
view.AddGlobal("version", version.Version)
view.AddGlobal("lang", ctx.Language)
view.AddGlobal("routeTo", func(entity interface{}, routeName string) string {
return routeRegistry.GetRouteForEntity(*ctx, entity, "")
})
view.AddGlobal("routeToWithName", func(entity interface{}, routeName string) string {
return routeRegistry.GetRouteForEntity(*ctx, entity, routeName)
})
view.AddGlobal("routeToSlug", func(slug string) string {
return routeRegistry.GetRouteForSlug(*ctx, slug, "")
})
view.AddGlobal("canonicalRouteToSlug", func(slug string) string {
// override the route prefix
ctxClone := *ctx
ctxClone.RoutePrefix = ""
return routeRegistry.GetRouteForSlug(ctxClone, slug, "")
})
view.AddGlobal("routeToSlugWithName", func(slug string, routeName string) string {
return routeRegistry.GetRouteForSlug(*ctx, slug, routeName)
})
view.AddGlobal("i18n", func(translationID string, args ...interface{}) string {
// jet will pass in numeric args as float64
// need to massage these back into expected types
/*
TranslateFunc returns the translation of the string identified by translationID.
If there is no translation for translationID, then the translationID itself is returned. This makes it easy to identify missing translations in your app.
If translationID is a non-plural form, then the first variadic argument may be a map[string]interface{} or struct that contains template data.
If translationID is a plural form, the function accepts two parameter signatures 1. T(count int, data struct{}) The first variadic argument must be an integer type (int, int8, int16, int32, int64) or a float formatted as a string (e.g. "123.45").
The second variadic argument may be a map[string]interface{} or struct{} that contains template data. 2. T(data struct{}) data must be a struct{} or
map[string]interface{} that contains a Count field and the template data,
Count field must be an integer type (int, int8, int16, int32, int64) or a float formatted as a string (e.g. "123.45").
*/
if len(args) == 1 {
argType := reflect.TypeOf(args[0])
argTypeName := argType.String()
if argTypeName == "string" {
if f, ok := args[0].(string); ok && len(f) == 0 {
log.Warningf("WARN: found empty string parameter while translating \"%s\". Set a default or ensure the argument is not empty in %s", translationID, ctx.Route.TemplatePath)
}
}
if argTypeName == "string" || strings.Contains(argTypeName, "int") || argTypeName == "map[string]interface {}" {
return trans(translationID, args[0])
}
if f, ok := args[0].(float64); ok {
return trans(translationID, int(f))
}
log.Errorf("WARN: translating %s found unrecognised type %s", translationID, argType)
}
return trans(translationID)
})
view.AddGlobal("config", func(key string, args ...string) string {
if s, ok := ctx.Site.Config[key]; ok {
return s
}
if len(args) > 0 {
return args[0]
}
return ""
})
view.AddGlobal("configInt", func(key string, args ...int) int {
return ctx.Site.Config.GetInt(key, args...)
})
view.AddGlobal("isEnabled", func(key string) bool {
return ctx.Site.Toggles[key]
})
return view
}
// ApplyContentTransforms - add the markdown / sanitization / shortcodes
func ApplyContentTransforms(data string) string {
// apply mark down
unsafe := blackfriday.Run([]byte(data))
// apply the templates
return insertTemplates(string(unsafe))
}
// insertTemplates applys any templates and sanitise the output
func insertTemplates(data string) string {
var p string
matches := templateTagRegex.FindAllStringSubmatchIndex(data, -1)
c := len(matches)
if c > 0 {
p = ""
for i := 0; i < c; i++ {
if i == 0 {
p = p + bluemonday.UGCPolicy().Sanitize(data[:matches[i][0]]) +
processTemplateTag(data[matches[i][0]:matches[i][1]])
}
if i == c-1 {
p = p + bluemonday.UGCPolicy().Sanitize(data[matches[i][1]:])
} else {
p = p + bluemonday.UGCPolicy().Sanitize(data[matches[i][1]:matches[i+1][0]]) +
processTemplateTag(data[matches[i+1][0]:matches[i+1][1]])
}
}
} else {
p = bluemonday.UGCPolicy().Sanitize(data)
}
return p
}
// ConfigureShortcodeTemplatePath sets the directory where the short codes
// will be loaded from
func ConfigureShortcodeTemplatePath(cfg *Config) {
if shortCodeView == nil {
// get the template view
shortCodeView = jet.NewHTMLSet(cfg.ShortCodePath())
// built-in templates
shortCodeView.LoadTemplate("echo.jet", "<div class=\"echo\">slug:{{slug}}</div>")
shortCodeView.LoadTemplate("youtube.jet", `
<div {{isset(class) ? "class=\"" + class + "\"" : "style=\"position: relative; padding-bottom: 56.25%; padding-top: 30px; height: 0; overflow: hidden;\"" | raw }} >
<iframe src="//www.youtube.com/embed/{{id}}" {{isset(class) ? "class=\"" + class + "\"" : "style=\"position: absolute; top: 0; left: 0; width: 100%; height: 100%;\"" | raw }}{{if isset(autoplay) && autoplay=="true" }} autoplay=1{{end}} allowfullscreen frameborder="0"></iframe>
</div>`)
}
}
func processTemplateTag(templateTag string) string {
templateName, data, err := parseParameters(templateTag)
w := bytes.NewBufferString("")
templatePath := fmt.Sprintf("%s.jet", templateName)
t, err := shortCodeView.GetTemplate(templatePath)
if err != nil {
log.Error("Template load error. Loading %s %s", templatePath, err)
return "Err"
}
if err = t.Execute(w, *data, nil); err != nil {
w.WriteString("<pre>")
w.WriteString(err.Error())
w.WriteString("</pre>")
log.Errorf("Template execute error: %s", err)
}
return string(w.Bytes())
}
// parse the template tag into the template and arguments
func parseParameters(templateTag string) (string, *jet.VarMap, error) {
parameters := strings.Fields(strings.Trim(templateTag, "{} "))
data := jet.VarMap{}
if len(parameters) > 1 {
for _, p := range parameters[1:] {
s := strings.Split(p, "=")
if len(s) == 2 {
data.Set(s[0], s[1])
}
}
}
return parameters[0], &data, nil
}