Skip to content

Commit

Permalink
Add loop template function to allow interation in templating.
Browse files Browse the repository at this point in the history
The loop function is helpful as it allows fixed number
interations which may be desirable to users. The change also
includes a documentation update to show loop usgae.

Closes #201
  • Loading branch information
jrasell committed Jul 4, 2018
1 parent aefe2e0 commit 53e93fc
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
34 changes: 34 additions & 0 deletions docs/templates.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,40 @@ Render:
localhost:3306
```

#### loop

Accepts varying parameters and differs its behavior based on those parameters as detailed below.

If loop is given a signle int input, it will loop up to, but not including the given integer from index 0:

Example:
```
[[ range $i := loop 3 ]]
this-is-loop[[ $i ]][[ end ]]
```

Render:
```
this-is-output0
this-is-output1
this-is-output2
```

If given two integers, this function will begin at the first integer and loop up to but not including the second integer:

Example:
```
[[ range $i := loop 3 6 ]]
this-is-loop[[ $i ]][[ end ]]
```

Render:
```
this-is-output3
this-is-output4
this-is-output5
```

#### timeNow

Returns the current ISO_8601 standard timestamp as a string in the timezone of the machine the rendering was triggered on.
Expand Down
26 changes: 26 additions & 0 deletions template/funcs.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package template

import (
"errors"
"fmt"
"text/template"
"time"

Expand All @@ -16,6 +17,7 @@ func funcMap(consulClient *consul.Client) template.FuncMap {
"consulKey": consulKeyFunc(consulClient),
"consulKeyExists": consulKeyExistsFunc(consulClient),
"consulKeyOrDefault": consulKeyOrDefaultFunc(consulClient),
"loop": loop,
"timeNow": timeNowFunc,
"timeNowUTC": timeNowUTCFunc,
"timeNowTimezone": timeNowTimezoneFunc(),
Expand Down Expand Up @@ -94,6 +96,30 @@ func consulKeyOrDefaultFunc(consulClient *consul.Client) func(string, string) (s
}
}

func loop(ints ...int64) (<-chan int64, error) {
var start, stop int64
switch len(ints) {
case 1:
start, stop = 0, ints[0]
case 2:
start, stop = ints[0], ints[1]
default:
return nil, fmt.Errorf("loop: wrong number of arguments, expected 1 or 2"+
", but got %d", len(ints))
}

ch := make(chan int64)

go func() {
for i := start; i < stop; i++ {
ch <- i
}
close(ch)
}()

return ch, nil
}

func timeNowFunc() string {
return time.Now().Format("2006-01-02T15:04:05Z07:00")
}
Expand Down

0 comments on commit 53e93fc

Please sign in to comment.