🎨 Improve built-in template func

This commit is contained in:
Daniel 2024-03-08 16:19:25 +08:00
parent f7b2966978
commit 4ce87d4eb3
No known key found for this signature in database
GPG key ID: 86211BA83DF03017
2 changed files with 14 additions and 11 deletions

View file

@ -20,14 +20,12 @@ import (
"bytes"
"errors"
"fmt"
"github.com/araddon/dateparse"
"io/fs"
"os"
"path/filepath"
"sort"
"strings"
"text/template"
"time"
"github.com/88250/gulu"
"github.com/88250/lute/ast"
@ -413,13 +411,4 @@ func SQLTemplateFuncs(templateFuncMap *template.FuncMap) {
retSpans = sql.SelectSpansRawStmt(stmt, 512)
return
}
(*templateFuncMap)["parseTime"] = func(dateStr string) time.Time {
now := time.Now()
retTime, err := dateparse.ParseIn(dateStr, now.Location())
if nil != err {
logging.LogWarnf("parse date [%s] failed [%s], return current time instead", dateStr, err)
return now
}
return retTime
}
}

View file

@ -18,9 +18,12 @@ package util
import (
"github.com/Masterminds/sprig/v3"
"github.com/araddon/dateparse"
"github.com/siyuan-note/logging"
"github.com/spf13/cast"
"math"
"text/template"
"time"
)
func BuiltInTemplateFuncs() (ret template.FuncMap) {
@ -33,6 +36,7 @@ func BuiltInTemplateFuncs() (ret template.FuncMap) {
ret["powf"] = powf
ret["log"] = log
ret["logf"] = logf
ret["parseTime"] = parseTime
return
}
@ -42,3 +46,13 @@ func log(a, b interface{}) int64 {
return int64(math.Log(cast.ToFloat64(a)) / math.Log(cast.ToFloat64(b)))
}
func logf(a, b interface{}) float64 { return math.Log(cast.ToFloat64(a)) / math.Log(cast.ToFloat64(b)) }
func parseTime(dateStr string) time.Time {
now := time.Now()
retTime, err := dateparse.ParseIn(dateStr, now.Location())
if nil != err {
logging.LogWarnf("parse date [%s] failed [%s], return current time instead", dateStr, err)
return now
}
return retTime
}