0
0
mirror of https://github.com/thegeeklab/wp-plugin-go.git synced 2024-11-25 09:30:39 +00:00
wp-plugin-go/template/functions.go

53 lines
811 B
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"
)
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
}
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)
}
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:]
}