salix/vars.go

43 lines
946 B
Go
Raw Normal View History

package salix
import (
2024-02-28 05:43:35 +00:00
"encoding/json"
2023-12-18 00:55:13 +00:00
"fmt"
"reflect"
"strings"
)
2023-11-01 19:00:44 +00:00
var globalVars = map[string]any{
"len": tmplLen,
2024-02-28 05:43:35 +00:00
"json": tmplJSON,
2023-11-01 19:00:44 +00:00
"toUpper": strings.ToUpper,
"toLower": strings.ToLower,
"hasPrefix": strings.HasPrefix,
"trimPrefix": strings.TrimPrefix,
"hasSuffix": strings.HasSuffix,
"trimSuffix": strings.TrimSuffix,
"trimSpace": strings.TrimSpace,
"equalFold": strings.EqualFold,
"count": strings.Count,
"split": strings.Split,
"join": strings.Join,
2024-02-28 05:43:35 +00:00
"replace": strings.Replace,
"replaceAll": strings.ReplaceAll,
2024-01-19 07:42:18 +00:00
"sprintf": fmt.Sprintf,
}
2023-12-18 00:55:13 +00:00
func tmplLen(v any) (int, error) {
val := reflect.ValueOf(v)
switch val.Kind() {
case reflect.Array, reflect.Slice, reflect.String, reflect.Map:
2023-12-18 00:55:13 +00:00
return val.Len(), nil
default:
2023-12-18 00:55:13 +00:00
return 0, fmt.Errorf("cannot get length of %T", v)
}
}
2024-02-28 05:43:35 +00:00
2024-03-01 23:25:29 +00:00
func tmplJSON(v any) (HTML, error) {
2024-02-28 05:43:35 +00:00
data, err := json.Marshal(v)
2024-03-01 23:25:29 +00:00
return HTML(data), err
2024-02-28 05:43:35 +00:00
}