0
0
mirror of https://github.com/thegeeklab/wp-plugin-go.git synced 2024-09-21 18:22:45 +02:00
wp-plugin-go/template/functions.go

53 lines
811 B
Go
Raw Normal View History

2023-02-08 13:42:55 +01:00
package template
import (
"fmt"
2023-02-08 13:42:55 +01:00
"text/template"
"unicode"
"unicode/utf8"
2023-02-08 13:42:55 +01:00
"github.com/Masterminds/sprig/v3"
)
func LoadFuncMap() template.FuncMap {
2023-02-08 13:42:55 +01:00
sprigFuncs := sprig.GenericFuncMap()
customFuncs := template.FuncMap{
"ToSentence": ToSentence,
}
2023-02-08 13:42:55 +01: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:]
}