2023-07-21 08:59:02 +00:00
|
|
|
package template
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2023-07-27 09:51:31 +00:00
|
|
|
"net/url"
|
2023-07-25 14:42:53 +00:00
|
|
|
"regexp"
|
2023-07-21 08:59:02 +00:00
|
|
|
"text/template"
|
|
|
|
)
|
|
|
|
|
|
|
|
type ErrFail struct {
|
|
|
|
msg string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (err ErrFail) Error() string {
|
|
|
|
return err.msg
|
|
|
|
}
|
|
|
|
|
2023-08-15 16:07:22 +00:00
|
|
|
type pair struct {
|
|
|
|
k string
|
|
|
|
v any
|
|
|
|
}
|
|
|
|
|
2023-07-21 08:59:02 +00:00
|
|
|
var helperFuncs = template.FuncMap{
|
|
|
|
"fail": func(format string, args ...any) (any, error) {
|
|
|
|
return nil, ErrFail{fmt.Sprintf(format, args...)}
|
|
|
|
},
|
2023-07-27 09:51:31 +00:00
|
|
|
// Alias for https://pkg.go.dev/net/url#Parse. Allows usage of all methods of url.URL
|
|
|
|
"url": func(rawUrl string) (*url.URL, error) {
|
|
|
|
return url.Parse(rawUrl)
|
|
|
|
},
|
2023-07-25 14:42:53 +00:00
|
|
|
// Alias for https://pkg.go.dev/regexp#Compile. Allows usage of all methods of regexp.Regexp
|
|
|
|
"regexp": func(expr string) (*regexp.Regexp, error) {
|
|
|
|
return regexp.Compile(expr)
|
|
|
|
},
|
2023-08-15 16:07:22 +00:00
|
|
|
// A key value pair. This is used with the map function to generate maps
|
|
|
|
// to use inside a template
|
|
|
|
"pair": func(k string, v any) pair {
|
|
|
|
return pair{k, v}
|
|
|
|
},
|
|
|
|
// map converts a list of pairs to a map object. This is useful to pass multiple
|
|
|
|
// objects to templates defined in the library directory. Go text template
|
|
|
|
// syntax for invoking a template only allows specifying a single argument,
|
|
|
|
// this function can be used to workaround that limitation.
|
|
|
|
//
|
|
|
|
// For example: {{template "my_template" (map (pair "foo" $arg1) (pair "bar" $arg2))}}
|
|
|
|
// $arg1 and $arg2 can be referred from inside "my_template" as ".foo" and ".bar"
|
|
|
|
"map": func(pairs ...pair) map[string]any {
|
|
|
|
result := make(map[string]any, 0)
|
|
|
|
for _, p := range pairs {
|
|
|
|
result[p.k] = p.v
|
|
|
|
}
|
|
|
|
return result
|
|
|
|
},
|
2023-07-21 08:59:02 +00:00
|
|
|
}
|