[英]How do I assign variables within a conditional
Given a YAML
file and go
templates, I can assign a variable with: 给定一个
YAML
文件并go
模板,我可以分配一个变量:
{{ $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
但是
foo
仍然是bar
This is not possible with Go 1.10 and earlier versions, template variables (identifiers) cannot be modified (there are "workarounds", see following link). 对于Go 1.10及更早版本,这是不可能的,模板变量(标识符)无法修改(有“变通办法”,请参阅以下链接)。 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.
它们可以在(n内部)块中重新声明/阴影,但是一旦您离开内部块,更改将不可见。 For details and workarounds, see In a Go template range loop, are variables declared outside the loop reset on each iteration?
有关详细信息和变通方法,请参阅In a Go模板范围循环,是否在每次迭代时在循环重置之外声明变量?
Note that however Go 1.11 is about to be released which will support this . 请注意,然而Go 1.11即将发布,这将支持这一点 。
This will be a valid and working template code starting with Go 1.11: 这将是一个从Go 1.11开始的有效且有效的模板代码:
{{ $v := "init" }}
{{ if true }}
{{ $v = "changed" }}
{{ end }}
v: {{ $v }} {{/* "changed" */}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.