-
Notifications
You must be signed in to change notification settings - Fork 9
/
view.go
56 lines (45 loc) · 1.07 KB
/
view.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
package web
import (
"bytes"
"html/template"
"io/ioutil"
"strings"
"github.com/pkg/errors"
)
func View(tplPath string, data interface{}) (string, error) {
tplContent, err := ioutil.ReadFile(tplPath)
if err != nil {
return "", errors.Wrap(err, "can not open template file")
}
funcMap := template.FuncMap{
"starts_with": startsWith,
"ends_with": endsWith,
}
tpl, err := template.New("").Funcs(funcMap).Parse(string(tplContent))
if err != nil {
return "", errors.Wrap(err, "parse template failed")
}
var buffer bytes.Buffer
if err := tpl.Execute(&buffer, data); err != nil {
return "", errors.Wrap(err, "execute template failed")
}
return buffer.String(), nil
}
// startsWith 判断是字符串开始
func startsWith(haystack string, needles ...string) bool {
for _, n := range needles {
if strings.HasPrefix(haystack, n) {
return true
}
}
return false
}
// endsWith 判断字符串结尾
func endsWith(haystack string, needles ...string) bool {
for _, n := range needles {
if strings.HasSuffix(haystack, n) {
return true
}
}
return false
}