1
0
mirror of https://github.com/danog/liquid.git synced 2024-11-27 08:34:42 +01:00

Implement ar.first, ar.list

This commit is contained in:
Oliver Steele 2017-06-28 09:50:04 -04:00
parent a4b1835d2c
commit c648a7030f
2 changed files with 18 additions and 8 deletions

View File

@ -29,10 +29,10 @@ var evaluatorTests = []struct {
{"ar[100]", nil}, {"ar[100]", nil},
{"obj[1]", nil}, {"obj[1]", nil},
{"obj.c[0]", "r"}, {"obj.c[0]", "r"},
// {`fruits.first`, "apples"}, {`fruits.first`, "apples"},
// {`fruits.last`, "plums"}, {`fruits.last`, "plums"},
// {`empty_list.first`, ""}, {`empty_list.first`, nil},
// {`empty_list.last`, ""}, {`empty_list.last`, nil},
// Operators // Operators
{"1 == 1", true}, {"1 == 1", true},

View File

@ -8,6 +8,16 @@ func makeObjectPropertyEvaluator(obj func(Context) interface{}, attr string) fun
return func(ctx Context) interface{} { return func(ctx Context) interface{} {
ref := reflect.ValueOf(obj(ctx)) ref := reflect.ValueOf(obj(ctx))
switch ref.Kind() { switch ref.Kind() {
case reflect.Array, reflect.Slice:
if ref.Len() == 0 {
return nil
}
switch attr {
case "first":
return ref.Index(0).Interface()
case "last":
return ref.Index(ref.Len() - 1).Interface()
}
case reflect.Map: case reflect.Map:
value := ref.MapIndex(reflect.ValueOf(attr)) value := ref.MapIndex(reflect.ValueOf(attr))
if value.Kind() != reflect.Invalid { if value.Kind() != reflect.Invalid {
@ -18,15 +28,15 @@ func makeObjectPropertyEvaluator(obj func(Context) interface{}, attr string) fun
} }
} }
func makeIndexEvaluator(obj, indexfn func(Context) interface{}) func(Context) interface{} { func makeIndexEvaluator(obj, index func(Context) interface{}) func(Context) interface{} {
return func(ctx Context) interface{} { return func(ctx Context) interface{} {
ref := reflect.ValueOf(obj(ctx)) ref := reflect.ValueOf(obj(ctx))
index := reflect.ValueOf(indexfn(ctx)) i := reflect.ValueOf(index(ctx))
switch ref.Kind() { switch ref.Kind() {
case reflect.Array, reflect.Slice: case reflect.Array, reflect.Slice:
switch index.Kind() { switch i.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
n := int(index.Int()) n := int(i.Int())
if n < 0 { if n < 0 {
n = ref.Len() + n n = ref.Len() + n
} }