Skip to content

Commit 42fa791

Browse files
orsiniummuesli
authored andcommitted
make filters kinda type safe
1 parent c7bae9a commit 42fa791

File tree

1 file changed

+23
-27
lines changed

1 file changed

+23
-27
lines changed

templatehelper/templatehelper.go

+23-27
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ package templatehelper
2323

2424
import (
2525
"encoding/json"
26+
"errors"
2627
htmlTemplate "html/template"
2728
"regexp"
2829
"strings"
@@ -37,46 +38,41 @@ var (
3738
json, _ := json.Marshal(values)
3839
return htmlTemplate.JS(json)
3940
},
40-
"Left": func(values ...interface{}) string {
41-
s := values[0].(string)
42-
n := values[1].(int)
41+
"Left": func(s string, n int) string {
4342
if n > len(s) {
4443
n = len(s)
4544
}
46-
4745
return s[:n]
4846
},
49-
"Matches": func(values ...interface{}) bool {
50-
ok, _ := regexp.MatchString(values[1].(string), values[0].(string))
51-
return ok
47+
"Matches": func(s string, pattern string) (bool, error) {
48+
return regexp.MatchString(pattern, s)
5249
},
53-
"Mid": func(values ...interface{}) string {
54-
s := values[0].(string)
55-
l := values[1].(int)
56-
if l > len(s) {
57-
l = len(s)
50+
"Mid": func(s string, left int, values ...int) string {
51+
if left > len(s) {
52+
left = len(s)
5853
}
5954

60-
if len(values) > 2 {
61-
r := values[2].(int)
62-
if r > len(s) {
63-
r = len(s)
55+
if len(values) != 0 {
56+
right := values[0]
57+
if right > len(s) {
58+
right = len(s)
6459
}
65-
return s[l:r]
60+
return s[left:right]
6661
}
67-
return s[l:]
62+
return s[left:]
6863
},
69-
"Right": func(values ...interface{}) string {
70-
s := values[0].(string)
71-
n := len(s) - values[1].(int)
72-
if n < 0 {
73-
n = 0
64+
"Right": func(s string, right int) string {
65+
left := len(s) - right
66+
if left < 0 {
67+
left = 0
7468
}
75-
76-
return s[n:]
69+
return s[left:]
7770
},
78-
"Last": func(values ...interface{}) string {
79-
return values[0].([]string)[len(values[0].([]string))-1]
71+
"Last": func(items []string) (string, error) {
72+
if len(items) == 0 {
73+
return "", errors.New("cannot get last element from empty slice")
74+
}
75+
return items[len(items)-1], nil
8076
},
8177
// strings functions
8278
"Compare": strings.Compare, // 1.5+ only

0 commit comments

Comments
 (0)