1

Following is my code to render the Addresses of the nodes with a service:

    {{range "service@datacenter" "passing"}}{{.Address}} {{end}}

What I want to do is limit the number of addresses that are rendered. For example, if there are 5 nodes registered as providers of "service", I would like is to print addresses of 2 of them only. What I think I should be doing is slicing the array, but I am not able to get the GO syntax right. This is something that I want but is not syntactically correct:

    {{range "service@datacenter" "passing" [0:2]}}{{.Address}} {{end}}

What is the correct way to do this?

Magnus
  • 73
  • 8
  • I know Go templates, but I don't know consul. Maybe something like `{{range $i := loop 2}}{{$service := (index (service "foo" "passing"))}}{{$service.Address}}{{end}}`? This will fail if there are less than two though. – Ainar-G Sep 20 '16 at 17:00
  • From what I have gathered, it seems like $service is an array so `{{$service.Address}}` threw an error as there is not .Address element in the $service. On top of that, how did we restrict the number of Addresses we print? I tried to work in this direction and tried to do a `{{$x := service "foo" "passing"}}{{range $i := loop 2}}{{$y := (index $x $i)}}{{$y.Address}}{{end}}`, but it gave 'index out of bound:0' error. Perhaps I am not using the index function right. – Magnus Sep 23 '16 at 14:10

1 Answers1

0

Found a solution to limit the number of array elements that can be rendered using consul-template.

    {{$x := service "service@datacenter" "passing"}}{{range $index, $element := $x}}{{if lt $index 2}}{{$element.Address}},{{end}}{{end}}

The range function provides an index variable along with the array element that can be used to check for the limit using the if block. Here the only two Addresses would be rendered.

Magnus
  • 73
  • 8