Go
1.11添加了对更改模板变量值的支持。要定义变量,请使用:=:
{ {$currentUserId := 0}}
要更改其值,请使用Assignment =:
{ {$currentUserId = .UserData.UserId}}
如果变量在{ {if}}块外创建但在块内更改,则更改将在{ {if}}块后可见。
{ {$currentUserId := 0 -}}
Before: { {$currentUserId}}
{ {if .UserData -}}
{ {$currentUserId = .UserData.UserId}}
{ {else}}
{ {$currentUserId = 0}}
{ {end}}
像这样测试:
m := map[string]interface{}{}
t := template.Must(template.New("").Parse(src))
m["UserData"] = UserData{99}
if err := t.Execute(os