@@ -23,6 +23,7 @@ package templatehelper
23
23
24
24
import (
25
25
"encoding/json"
26
+ "errors"
26
27
htmlTemplate "html/template"
27
28
"regexp"
28
29
"strings"
@@ -37,46 +38,41 @@ var (
37
38
json , _ := json .Marshal (values )
38
39
return htmlTemplate .JS (json )
39
40
},
40
- "Left" : func (values ... interface {}) string {
41
- s := values [0 ].(string )
42
- n := values [1 ].(int )
41
+ "Left" : func (s string , n int ) string {
43
42
if n > len (s ) {
44
43
n = len (s )
45
44
}
46
-
47
45
return s [:n ]
48
46
},
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 )
52
49
},
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 )
58
53
}
59
54
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 )
64
59
}
65
- return s [l : r ]
60
+ return s [left : right ]
66
61
}
67
- return s [l :]
62
+ return s [left :]
68
63
},
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
74
68
}
75
-
76
- return s [n :]
69
+ return s [left :]
77
70
},
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
80
76
},
81
77
// strings functions
82
78
"Compare" : strings .Compare , // 1.5+ only
0 commit comments