2015-07-10 18:28:55 +00:00
|
|
|
package filters
|
|
|
|
|
2017-11-22 20:55:05 +00:00
|
|
|
import (
|
|
|
|
"time"
|
|
|
|
|
|
|
|
humanize "github.com/flosch/go-humanize"
|
|
|
|
"github.com/flosch/pongo2"
|
|
|
|
)
|
2015-07-10 18:28:55 +00:00
|
|
|
|
|
|
|
func init() {
|
|
|
|
pongo2.RegisterFilter("lastNItems", filterLastNItems)
|
2017-11-22 20:55:05 +00:00
|
|
|
pongo2.RegisterFilter("naturaltime", filterTimeuntilTimesince)
|
2015-07-10 18:28:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func filterLastNItems(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) {
|
|
|
|
if !in.CanSlice() {
|
|
|
|
return in, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
from := in.Len() - param.Integer()
|
2016-01-23 11:53:04 +00:00
|
|
|
if from < 0 {
|
|
|
|
from = 0
|
|
|
|
}
|
|
|
|
|
2015-07-10 18:28:55 +00:00
|
|
|
return in.Slice(from, in.Len()), nil
|
|
|
|
}
|
2017-11-22 20:55:05 +00:00
|
|
|
|
|
|
|
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
|
|
|
|
}
|