3

Given a YAML file and go templates, I can assign a variable with:

{{ $foo := "bar" }}

And I can use a conditional like:

{{ if eq $foo "bar" }} jim {{ else }} bob {{ end }}

How do I combine the two to assign the result of a condition to a variable?

I've tried:

{{ $foo := "bar" }}

{{ if eq $foo "bar" }}
{{ $foo = "jim" }} 
{{ else }}
{{ $foo = "bob" }}
{{ end }}

But foo remains bar

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
noamt
  • 7,397
  • 2
  • 37
  • 59
  • 3
    This kind of logic is generally best kept out of templates, either by doing the logic and passing the correct value in with the template data, or by adding a custom template function to do the logic. – Adrian Aug 22 '18 at 15:06

1 Answers1

4

This is not possible with Go 1.10 and earlier versions, template variables (identifiers) cannot be modified (there are "workarounds", see following link). They can be re-declared / shadowed in a(n inner) block, but once you are out of the inner block, the changes will not be visible. For details and workarounds, see In a Go template range loop, are variables declared outside the loop reset on each iteration?

Note that however Go 1.11 is about to be released which will support this.

This will be a valid and working template code starting with Go 1.11:

{{ $v := "init" }}
{{ if true }}
  {{ $v = "changed" }}
{{ end }}
v: {{ $v }} {{/* "changed" */}}
icza
  • 389,944
  • 63
  • 907
  • 827