2021-01-09 17:54:50 +00:00
|
|
|
package helpers
|
|
|
|
|
|
|
|
import (
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/aymerick/raymond"
|
2021-01-09 18:48:29 +00:00
|
|
|
"github.com/mickael-menu/zk/core/style"
|
2021-01-09 17:54:50 +00:00
|
|
|
"github.com/mickael-menu/zk/util"
|
|
|
|
)
|
|
|
|
|
|
|
|
// RegisterStyle register the {{style}} template helpers which stylizes the
|
|
|
|
// text input according to predefined styling rules.
|
|
|
|
//
|
|
|
|
// {{style "date" created}}
|
|
|
|
// {{#style "red"}}Hello, world{{/style}}
|
2021-01-09 18:48:29 +00:00
|
|
|
func RegisterStyle(styler style.Styler, logger util.Logger) {
|
2021-01-09 17:54:50 +00:00
|
|
|
style := func(keys string, text string) string {
|
2021-01-09 18:48:29 +00:00
|
|
|
rules := make([]style.Rule, 0)
|
2021-01-09 17:54:50 +00:00
|
|
|
for _, key := range strings.Fields(keys) {
|
2021-01-09 18:48:29 +00:00
|
|
|
rules = append(rules, style.Rule(key))
|
2021-01-09 17:54:50 +00:00
|
|
|
}
|
|
|
|
res, err := styler.Style(text, rules...)
|
|
|
|
if err != nil {
|
|
|
|
logger.Err(err)
|
|
|
|
return text
|
|
|
|
} else {
|
|
|
|
return res
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
raymond.RegisterHelper("style", func(rules string, opt interface{}) string {
|
|
|
|
switch arg := opt.(type) {
|
|
|
|
case *raymond.Options:
|
|
|
|
return style(rules, arg.Fn())
|
|
|
|
case string:
|
|
|
|
return style(rules, arg)
|
|
|
|
default:
|
|
|
|
logger.Printf("the {{style}} template helper is expecting a string as input, received: %v", opt)
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|