-
Notifications
You must be signed in to change notification settings - Fork 25
/
template_funcmap.go
82 lines (69 loc) · 1.49 KB
/
template_funcmap.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
package templates
import (
"strings"
"text/template"
"unicode"
"github.com/serenize/snaker"
)
func EsimFuncMap() map[string]interface{} {
return template.FuncMap{
"tolower": strings.ToLower,
"cutFirstToLower": CutFirstToLower,
"firstToLower": FirstToLower,
"snakeToCamel": snaker.SnakeToCamel,
"snakeToCamelLower": snaker.SnakeToCamelLower,
"shorten": Shorten,
}
}
// Abc => a.
func CutFirstToLower(s string) string {
if s == "" {
return s
}
return strings.ToLower(string([]rune(s)[0]))
}
// Abc => abc.
func FirstToLower(s string) string {
if s == "" {
return s
}
return strings.ToLower(string([]rune(s)[0])) + string([]rune(s)[1:])
}
func FirstToUpper(s string) string {
if s == "" {
return s
}
return strings.ToUpper(string([]rune(s)[0])) + string([]rune(s)[1:])
}
// Shorten shorten the string.
func Shorten(s string) string {
if s == "" {
return s
}
var result string
var words []rune
var max = 3
rs := []rune(s)
for i := 0; i < len(rs); i++ {
if unicode.IsUpper(rs[i]) {
words = append(words, rs[i])
} else if i == 0 && unicode.IsLower(rs[i]) {
words = append(words, rs[i])
} else if string(rs[i]) == "_" || string(rs[i]) == "-" {
if unicode.IsUpper(rs[i+1]) || unicode.IsLower(rs[i+1]) {
words = append(words, rs[i+1])
}
}
}
if len(words) > 0 {
for k, word := range words {
if k >= max {
continue
}
result += string(word)
}
} else {
result = s[0:max]
}
return strings.ToLower(result)
}