From c28df761d1da128315ecae6b021a75326afb692a Mon Sep 17 00:00:00 2001 From: Elara6331 Date: Tue, 27 Feb 2024 21:43:35 -0800 Subject: [PATCH] Add a few new default functions --- README.md | 3 +++ vars.go | 9 +++++++++ 2 files changed, 12 insertions(+) diff --git a/README.md b/README.md index 65d78b0..5145fd3 100644 --- a/README.md +++ b/README.md @@ -170,6 +170,7 @@ Functions used in a template can accept any number of arguments but are limited Salix includes several useful global functions in all templates: - `len(v any) int`: Returns the length of the value passed in. If the length can't be found for the value passed in, it returns an error. +- `json(v any) string`: Returns a JSON string for the value passed in. - `toUpper(s string) string`: Returns `s`, but with all characters mapped to their uppercase equivalents. - `toLower(s string) string`: Returns `s`, but with all characters mapped to their lowercase equivalents. - `hasPrefix(s, prefix string) bool`: Returns true if `s` starts with `prefix`. @@ -181,6 +182,8 @@ Salix includes several useful global functions in all templates: - `count(s, substr string) int`: Returns the amount of times that `substr` appears in `s`. - `split(s, sep string) []string`: Returns a slice containing all substrings separated by `sep`. - `join(ss []string, sep string) string`: Returns a string with all substrings in `ss` joined by `sep`. +- `replace(s, old, new string, n int)`: Returns a string with `n` occurrences of `old` in `s` replaced with `new`. +- `replaceAll(s, old, new string)`: Returns a string with all occurrences of `old` in `s` replaced with `new`. ### Adding Custom Functions diff --git a/vars.go b/vars.go index 2a65d03..8c689e7 100644 --- a/vars.go +++ b/vars.go @@ -1,6 +1,7 @@ package salix import ( + "encoding/json" "fmt" "reflect" "strings" @@ -8,6 +9,7 @@ import ( var globalVars = map[string]any{ "len": tmplLen, + "json": tmplJSON, "toUpper": strings.ToUpper, "toLower": strings.ToLower, "hasPrefix": strings.HasPrefix, @@ -19,6 +21,8 @@ var globalVars = map[string]any{ "count": strings.Count, "split": strings.Split, "join": strings.Join, + "replace": strings.Replace, + "replaceAll": strings.ReplaceAll, "sprintf": fmt.Sprintf, } @@ -31,3 +35,8 @@ func tmplLen(v any) (int, error) { return 0, fmt.Errorf("cannot get length of %T", v) } } + +func tmplJSON(v any) (string, error) { + data, err := json.Marshal(v) + return string(data), err +}