0
0
mirror of https://github.com/thegeeklab/wp-plugin-go.git synced 2024-11-27 02:10:35 +00:00
wp-plugin-go/template/functions.go

59 lines
1.2 KiB
Go
Raw Normal View History

2023-02-08 12:42:55 +00:00
package template
import (
"fmt"
2023-02-08 12:42:55 +00:00
"text/template"
"unicode"
"unicode/utf8"
2023-02-08 12:42:55 +00:00
"github.com/Masterminds/sprig/v3"
)
2024-03-11 08:23:17 +00:00
// LoadFuncMap merges the sprig template functions with any custom functions
// provided, giving priority to the custom functions in case of collisions.
func LoadFuncMap() template.FuncMap {
2023-02-08 12:42:55 +00:00
sprigFuncs := sprig.GenericFuncMap()
customFuncs := template.FuncMap{
"ToSentence": ToSentence,
}
2023-02-08 12:42:55 +00:00
for name, f := range customFuncs {
if _, ok := sprigFuncs[name]; ok {
continue
}
sprigFuncs[name] = f
}
return sprigFuncs
}
2024-03-11 08:23:17 +00:00
// ToSentence capitalizes the first letter of the input string,
// adds a period at the end if needed, and returns the resulting sentence.
func ToSentence(s string) string {
if s == "" {
return ""
}
r, n := utf8.DecodeRuneInString(s)
closer := ""
if getLastRune(s, 1) != "." {
closer = "."
}
return fmt.Sprintf("%s%s%s", string(unicode.ToUpper(r)), s[n:], closer)
}
2024-03-11 08:23:17 +00:00
// getLastRune returns the last n runes in the string s.
// It decodes s from the end, counting n runes.
func getLastRune(s string, c int) string {
j := len(s)
for i := 0; i < c && j > 0; i++ {
_, size := utf8.DecodeLastRuneInString(s[:j])
j -= size
}
return s[j:]
}