diff --git a/docs/templates.md b/docs/templates.md index cee2c25fb..72ccdec3d 100644 --- a/docs/templates.md +++ b/docs/templates.md @@ -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. diff --git a/template/funcs.go b/template/funcs.go index a977ba4af..01150266c 100644 --- a/template/funcs.go +++ b/template/funcs.go @@ -2,6 +2,7 @@ package template import ( "errors" + "fmt" "text/template" "time" @@ -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(), @@ -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") }