Format provided date with the {{date}} template helper

pull/6/head
Mickaël Menu 3 years ago
parent 8a876f3b7f
commit 05f384bbe0
No known key found for this signature in database
GPG Key ID: 53D73664CD359895

@ -92,9 +92,6 @@ func TestSlugHelper(t *testing.T) {
}
func TestDateHelper(t *testing.T) {
// Default
testString(t, "{{date}}", nil, "2009-11-17")
test := func(format string, expected string) {
testString(t, fmt.Sprintf("{{date '%s'}}", format), nil, expected)
}
@ -108,6 +105,10 @@ func TestDateHelper(t *testing.T) {
test("timestamp", "200911172034")
test("timestamp-unix", "1258490098")
test("cust: %Y-%m", "cust: 2009-11")
// Test with provided date
context := map[string]interface{}{"created": time.Date(2009, 11, 17, 20, 34, 58, 651387237, time.UTC)}
testString(t, "{{date created '%Y-%m'}}", context, "2009-11")
}
func TestShellHelper(t *testing.T) {

@ -1,6 +1,8 @@
package helpers
import (
"time"
"github.com/aymerick/raymond"
"github.com/lestrrat-go/strftime"
"github.com/mickael-menu/zk/util"
@ -12,19 +14,26 @@ import (
// It supports various styles: short, medium, long, full, year, time,
// timestamp, timestamp-unix or a custom strftime format.
//
// {{date}} -> 2009-11-17
// {{date "medium"}} -> Nov 17, 2009
// {{date "%Y-%m"}} -> 2009-11
// {{date created "%Y-%m-%d"}} -> 2008-12-05
func RegisterDate(logger util.Logger, date date.Provider) {
raymond.RegisterHelper("date", func(opt interface{}) string {
raymond.RegisterHelper("date", func(arg1 interface{}, arg2 interface{}) string {
format := "%Y-%m-%d"
date := date.Date()
switch arg := arg1.(type) {
case string:
format = findFormat(arg)
case time.Time:
date = arg
}
arg, ok := opt.(string)
if ok {
if arg, ok := arg2.(string); ok {
format = findFormat(arg)
}
res, err := strftime.Format(format, date.Date(), strftime.WithUnixSeconds('s'))
res, err := strftime.Format(format, date, strftime.WithUnixSeconds('s'))
if err != nil {
logger.Printf("the {{date}} template helper failed to format the date: %v", err)
return ""

Loading…
Cancel
Save