Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add loop template function to allow iteration in templating. #202

Merged
merged 1 commit into from
Jul 4, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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