add template functions

This commit is contained in:
2026-06-03 00:23:08 +06:30
parent d7ffc17d71
commit d8781c3981
6 changed files with 146 additions and 10 deletions

78
img.go
View File

@@ -24,7 +24,13 @@ import (
"github.com/kenshaw/escpos"
)
import "log"
import (
"log"
"strconv"
"golang.org/x/text/language"
"golang.org/x/text/message"
)
const (
defalutFontSize = 18.0
@@ -102,8 +108,13 @@ func GenImg(width int, outputPath, payload, tmpl string) string {
return r
}
var funcMap = template.FuncMap{
"formatNumber": FormatNumber,
"div": Div,
}
func renderTemplate(tmp string, data map[string]interface{}) (string, error) {
tmpl, err := template.New("mytemplate").Parse(tmp)
tmpl, err := template.New("mytemplate").Funcs(funcMap).Parse(tmp)
if err != nil {
return "", err
}
@@ -431,3 +442,66 @@ func nodeHeight(n *html.Node, dc *gg.Context, canvasWidth int, xPadding, yPaddin
}
return y
}
type RealNumber interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 |
~float32 | ~float64
}
func FormatNumber(precision int, b any) string {
return GenericFormatNumber(precision, convertToFloat64(b))
}
func GenericFormatNumber[T RealNumber](precision int, v T) string {
pEnglish := message.NewPrinter(language.English)
n := float64(v)
s := fmt.Sprintf("%.*f", precision, n)
parts := strings.Split(s, ".")
intPart := parts[0]
i, err := strconv.Atoi(intPart)
if err != nil {
return ""
}
out := pEnglish.Sprintf("%d", i)
if len(parts) > 1 {
return out + "." + parts[1]
}
return out
}
func Div(a, b any) float64 {
return GenericDiv(convertToFloat64(a), convertToFloat64(b))
}
func GenericDiv[T RealNumber](a, b T) float64 {
floatB := float64(b)
if floatB == 0 {
return 0
}
return float64(a) / floatB
}
func convertToFloat64(v any) float64 {
switch t := v.(type) {
case float64:
return t
case float32:
return float64(t)
case int:
return float64(t)
case int64:
return float64(t)
case int32:
return float64(t)
case uint:
return float64(t)
case uint64:
return float64(t)
default:
return 0
}
}