Add the `get-date` template helper (#262)

pull/266/head
Zach Leslie 2 years ago committed by GitHub
parent c21c4fc21f
commit 404ef9d6f5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -7,6 +7,14 @@ All notable changes to this project will be documented in this file.
### Added
* LSP: Support for external URLs with `documentLink`.
* New `{{get-date}}` template helper to obtain a date object from natural language.
```
Get a relative date using natural language:
{{get-date "next week"}}
Format a date returned by `get-date`:
{{date (get-date "monday") "timestamp"}}
```
### Fixed

@ -15,13 +15,14 @@ import (
func Init(supportsUTF8 bool, logger util.Logger) {
helpers.RegisterConcat()
helpers.RegisterSubstring()
helpers.RegisterDate(logger)
helpers.RegisterGetDate(logger)
helpers.RegisterJoin()
helpers.RegisterJSON(logger)
helpers.RegisterList(supportsUTF8)
helpers.RegisterPrepend(logger)
helpers.RegisterShell(logger)
helpers.RegisterSubstring()
}
// Template renders a parsed handlebars template.

@ -241,6 +241,11 @@ func TestDateHelper(t *testing.T) {
testString(t, "{{date now 'elapsed'}}", context, "13 years ago")
}
func TestGetDateHelper(t *testing.T) {
context := map[string]interface{}{"now": time.Date(2009, 11, 17, 20, 34, 58, 651387237, time.UTC)}
testString(t, "{{get-date \"2009-11-17T20:34:58\"}}", context, "2009-11-17 20:34:58 +0000 UTC")
}
func TestShellHelper(t *testing.T) {
// block is passed as piped input
testString(t,

@ -0,0 +1,23 @@
package helpers
import (
"time"
"github.com/aymerick/raymond"
"github.com/mickael-menu/zk/internal/util"
dateutil "github.com/mickael-menu/zk/internal/util/date"
"github.com/pkg/errors"
)
// RegisterGetDate registers the {{getdate}} template helper to use the `naturaldate` package to generate time.Time based on language strings.
// This can be used in combination with the `date` helper to generate dates in the user's language.
// {{date (get-date "last week") "timestamp"}}
func RegisterGetDate(logger util.Logger) {
raymond.RegisterHelper("get-date", func(natural string) time.Time {
date, err := dateutil.TimeFromNatural(natural)
if err != nil {
logger.Err(errors.Wrap(err, "the {{get-date}} template helper failed to parse the date"))
}
return date
})
}

@ -3,7 +3,7 @@ package date
import (
"time"
"github.com/tj/go-naturaldate"
naturaldate "github.com/tj/go-naturaldate"
)
// Provider returns a date instance.

Loading…
Cancel
Save