Home > Back-end >  Calling subtemplates from within a loop in Go template
Calling subtemplates from within a loop in Go template

Time:10-21

When I am importing a subtemplate outside of a {{ range }} loop, variables are passed successfully inside the imported template:

...
 {{ template "userdata" . }}
...

(here, I can access my outer templates variables in the inner template userdata). So far so good.

However same fashion import doesn't work when being called inside a {{ range }} loop:

...
{{ range $instance := .Instances }}
- type: instance
  metadata:
    userdata: {{ template "userdata" . }}
...

Above ends with error messaging out something like:

Error: template: template.tmpl:3:46: executing "userdata" at <XXX>: can't evaluate field XXX in type int`

As far as I understand, it shadow my context variable with the loop iterator variable, and so it does not work.

How am I supposed to do it properly?

How do I pass the value of . outside of the range loop to template "userdata" when inside a range loop?

CodePudding user response:

Assign the value of . to a variable. Use the variable in the loop:

...
{{$x := .}}
{{ range $instance := .Instances }}
- type: instance
  metadata:
    userdata: {{ template "userdata" $x }}
...

If . is the root value in the template, then use $ to refer to that value:

...
{{ range $instance := .Instances }}
- type: instance
  metadata:
    userdata: {{ template "userdata" $ }}
...

Run it on the playground.

  • Related