1
0
mirror of https://github.com/Luzifer/mondash.git synced 2024-09-19 17:02:58 +00:00
mondash/filters/filter.go
Knut Ahlers fadd08d920
Extract required filter from pongo2-addons
Current version of pongo2-addons only works with master branch and is
not versioned. Also current version of prongo2-addons contains errors
related to markdown parser which is not used within mondash.

Signed-off-by: Knut Ahlers <knut@ahlers.me>
2017-11-22 21:55:05 +01:00

51 lines
1.1 KiB
Go

package filters
import (
"time"
humanize "github.com/flosch/go-humanize"
"github.com/flosch/pongo2"
)
func init() {
pongo2.RegisterFilter("lastNItems", filterLastNItems)
pongo2.RegisterFilter("naturaltime", filterTimeuntilTimesince)
}
func filterLastNItems(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) {
if !in.CanSlice() {
return in, nil
}
from := in.Len() - param.Integer()
if from < 0 {
from = 0
}
return in.Slice(from, in.Len()), nil
}
func filterTimeuntilTimesince(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) {
basetime, isTime := in.Interface().(time.Time)
if !isTime {
return nil, &pongo2.Error{
Sender: "filter:timeuntil/timesince",
ErrorMsg: "time-value is not a time.Time-instance",
}
}
var paramtime time.Time
if !param.IsNil() {
paramtime, isTime = param.Interface().(time.Time)
if !isTime {
return nil, &pongo2.Error{
Sender: "filter:timeuntil/timesince",
ErrorMsg: "time-parameter is not a time.Time-instance",
}
}
} else {
paramtime = time.Now()
}
return pongo2.AsValue(humanize.TimeDuration(basetime.Sub(paramtime))), nil
}