1
0
mirror of https://github.com/danog/gojekyll.git synced 2025-01-22 20:51:24 +01:00
gojekyll/liquid_filters.go
2017-06-15 10:17:30 -04:00

78 lines
1.8 KiB
Go

package main
import (
"encoding/json"
"reflect"
"github.com/acstech/liquid"
"github.com/acstech/liquid/core"
)
func init() {
liquid.Tags["link"] = LinkFactory
core.RegisterFilter("jsonify", JsonifyFactory)
core.RegisterFilter("where_exp", WhereExpFactory)
}
// JsonifyFactory implements the Jekyll `json` filter
func JsonifyFactory(parameters []core.Value) core.Filter {
if len(parameters) != 0 {
panic("The json filter doesn't accept parameters")
}
return func(input interface{}, data map[string]interface{}) interface{} {
s, err := json.Marshal(input)
if err != nil {
panic(err)
}
return s
}
}
// WhereExpFactory implements the Jekyll `where_exp` filter
func WhereExpFactory(parameters []core.Value) core.Filter {
if len(parameters) != 2 {
panic("The were_exp filter requires two parameters")
}
return (&WhereExpFilter{parameters[0], parameters[1]}).Run
}
// WhereExpFilter implements the Jekyll `where_exp` filter
type WhereExpFilter struct {
varName core.Value
expr core.Value
}
// Run implements the Jekyll `where_exp` filter
func (f *WhereExpFilter) Run(input interface{}, data map[string]interface{}) interface{} {
rt := reflect.ValueOf(input)
switch rt.Kind() {
case reflect.Slice:
case reflect.Array:
default:
return input
}
varName := f.varName.Resolve(data).(string)
expr := f.expr.Resolve(data).(string)
p := core.NewParser([]byte(expr + "%}"))
condition, err := p.ReadConditionGroup()
// TODO assert we're at the end of the string
if err != nil {
panic(err)
}
result := []interface{}{}
d := make(map[string]interface{})
for k, v := range data {
d[k] = v
}
for i := 0; i < rt.Len(); i++ {
item := rt.Index(i).Interface()
d[varName] = item
if condition.IsTrue(d) {
result = append(result, item)
}
}
return result
}