Skip to content

Commit

Permalink
Merge pull request #65 from aisbergg/feat-range-exp
Browse files Browse the repository at this point in the history
Allow range expression as general expressions (not only loops)
  • Loading branch information
danog committed Sep 24, 2023
2 parents 3170e91 + 28d8c66 commit 5dfb339
Show file tree
Hide file tree
Showing 5 changed files with 15 additions and 0 deletions.
1 change: 1 addition & 0 deletions tags/iteration_tags_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ var iterationTests = []struct{ in, expected string }{
// range
{`{% for i in (3 .. 5) %}{{i}}.{% endfor %}`, "3.4.5."},
{`{% for i in (3..5) %}{{i}}.{% endfor %}`, "3.4.5."},
{`{% assign l = (3..5) %}{% for i in l %}{{i}}.{% endfor %}`, "3.4.5."},

// tablerow
{`{% tablerow product in products %}{{ product }}{% endtablerow %}`,
Expand Down
1 change: 1 addition & 0 deletions tags/standard_tags_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ var tagTests = []struct{ in, expected string }{
// variable tags
{`{% assign av = 1 %}{{ av }}`, "1"},
{`{% assign av = obj.a %}{{ av }}`, "1"},
{`{% assign av = (1..5) %}{{ av }}`, "{1 5}"},
{`{% capture x %}captured{% endcapture %}{{ x }}`, "captured"},

// TODO research whether Liquid requires matching interior tags
Expand Down
2 changes: 2 additions & 0 deletions values/convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,8 @@ func Convert(value interface{}, typ reflect.Type) (interface{}, error) { // noli
result = reflect.Append(result, ev.Convert(et))
}
return result.Interface(), nil
} else if r, ok := value.(Range); ok {
return r.AsArray(), nil
}
switch rv.Kind() {
case reflect.Array, reflect.Slice:
Expand Down
2 changes: 2 additions & 0 deletions values/convert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,8 @@ var convertTests = []struct {
{yaml.MapSlice{{Key: "a", Value: 1}}, map[string]string{"a": "1"}},
{yaml.MapSlice{{Key: "a", Value: nil}}, map[string]interface{}{"a": nil}},
{yaml.MapSlice{{Key: nil, Value: 1}}, map[interface{}]string{nil: "1"}},
{Range{1, 5}, []interface{}{1, 2, 3, 4, 5}},
{Range{0, 0}, []interface{}{0}},
// {"March 14, 2016", time.Now(), timeMustParse("2016-03-14T00:00:00Z")},
{redConvertible{}, "red"},
}
Expand Down
9 changes: 9 additions & 0 deletions values/range.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,12 @@ func (r Range) Len() int { return r.e + 1 - r.b }

// Index is in the iteration interface
func (r Range) Index(i int) interface{} { return r.b + i }

// AsArray converts the range into an array.
func (r Range) AsArray() []interface{} {
a := make([]interface{}, 0, r.Len())
for i := r.b; i <= r.e; i++ {
a = append(a, i)
}
return a
}

0 comments on commit 5dfb339

Please sign in to comment.