1
0
mirror of https://github.com/danog/liquid.git synced 2024-12-02 17:28:38 +01:00
liquid/filters/filters.go

84 lines
1.8 KiB
Go
Raw Normal View History

2017-06-27 19:36:38 +02:00
// Package filters defines the standard Liquid filters.
2017-06-27 18:06:24 +02:00
package filters
import (
"encoding/json"
"fmt"
"strings"
"time"
2017-06-27 18:06:24 +02:00
2017-06-27 22:53:34 +02:00
"github.com/leekchan/timeutil"
2017-06-27 18:06:24 +02:00
"github.com/osteele/liquid/expressions"
"github.com/osteele/liquid/generics"
)
// DefineStandardFilters defines the standard Liquid filters.
func DefineStandardFilters() {
// values
expressions.DefineFilter("default", func(in, defaultValue interface{}) interface{} {
if in == nil || in == false || generics.IsEmpty(in) {
in = defaultValue
}
return in
})
// dates
2017-06-27 22:53:34 +02:00
expressions.DefineFilter("date", func(in, iformat interface{}) interface{} {
format, ok := iformat.(string)
if !ok {
format = "%a, %b %d, %y"
}
2017-06-27 22:53:34 +02:00
switch date := in.(type) {
case string:
d, err := generics.ParseTime(date)
if err != nil {
panic(err)
}
return timeutil.Strftime(&d, format)
case time.Time:
2017-06-27 22:53:34 +02:00
return timeutil.Strftime(&date, format)
default:
2017-06-27 22:53:34 +02:00
panic(expressions.UnimplementedError(fmt.Sprintf("date conversion from %v", date)))
}
})
2017-06-27 18:06:24 +02:00
// lists
expressions.DefineFilter("join", joinFilter)
expressions.DefineFilter("sort", sortFilter)
// strings
expressions.DefineFilter("split", splitFilter)
// Jekyll
expressions.DefineFilter("inspect", json.Marshal)
}
func joinFilter(in []interface{}, sep interface{}) interface{} {
a := make([]string, len(in))
s := ", "
if sep != nil {
s = fmt.Sprint(sep)
}
for i, x := range in {
a[i] = fmt.Sprint(x)
}
return strings.Join(a, s)
}
func sortFilter(in []interface{}, key interface{}) []interface{} {
out := make([]interface{}, len(in))
for i, v := range in {
out[i] = v
}
if key == nil {
generics.Sort(out)
} else {
generics.SortByProperty(out, key.(string))
}
return out
}
func splitFilter(in, sep string) interface{} {
return strings.Split(in, sep)
}