如何在模板中声明全局变量?
How to declare a global variable in a template?
我需要编写一个模板,首先定义一些变量,然后在模板生成的内容中使用它们:
{{ if $value.Env.CADDY_URL }}
{{ $url := $value.Env.CADDY_URL }}
{{ else }}
{{ $url := printf "http://%s.example.info" $value.Name }}
{{ end }}
{{/* more template */}}
{{/* and here I would like to use $url defined above */}}
{{ $url }}
我收到错误
undefined variable "$url"
阅读 documentation,我看到
A variable's scope extends to the "end" action of the control structure ("if", "with", or "range") in which it is declared, or to the end of the template if there is no such control structure.
这是否意味着没有全局(或整个模板范围)变量?或者有没有办法定义 $url
以便以后可以在模板中重复使用?
变量是有范围的。您在 {{if}}
和 {{else}}
块内创建 $url
变量,因此它们在这些块之外不可见。
在 {{if}}
之前创建变量,并使用赋值 =
而不是声明 :=
:
{{$url := ""}}
{{ if . }}
{{ $url = "http://true.com" }}
{{ else }}
{{ $url = "http://false.com" }}
{{ end }}
{{ $url }}
正在测试:
t := template.Must(template.New("").Parse(src))
fmt.Println(t.Execute(os.Stdout, true))
fmt.Println(t.Execute(os.Stdout, false))
输出(在 Go Playground 上尝试):
http://true.com<nil>
http://false.com<nil>
注意: Go 1.11 中添加了使用赋值修改模板变量,因此您需要使用 Go 1.11 或更新版本构建您的应用程序。如果您使用的是旧版本,则无法修改模板变量的值。
编辑: 我发现了一个副本:
你可以模仿早期版本的"changeable template variables",例子见这个问题:
我需要编写一个模板,首先定义一些变量,然后在模板生成的内容中使用它们:
{{ if $value.Env.CADDY_URL }}
{{ $url := $value.Env.CADDY_URL }}
{{ else }}
{{ $url := printf "http://%s.example.info" $value.Name }}
{{ end }}
{{/* more template */}}
{{/* and here I would like to use $url defined above */}}
{{ $url }}
我收到错误
undefined variable "$url"
阅读 documentation,我看到
A variable's scope extends to the "end" action of the control structure ("if", "with", or "range") in which it is declared, or to the end of the template if there is no such control structure.
这是否意味着没有全局(或整个模板范围)变量?或者有没有办法定义 $url
以便以后可以在模板中重复使用?
变量是有范围的。您在 {{if}}
和 {{else}}
块内创建 $url
变量,因此它们在这些块之外不可见。
在 {{if}}
之前创建变量,并使用赋值 =
而不是声明 :=
:
{{$url := ""}}
{{ if . }}
{{ $url = "http://true.com" }}
{{ else }}
{{ $url = "http://false.com" }}
{{ end }}
{{ $url }}
正在测试:
t := template.Must(template.New("").Parse(src))
fmt.Println(t.Execute(os.Stdout, true))
fmt.Println(t.Execute(os.Stdout, false))
输出(在 Go Playground 上尝试):
http://true.com<nil>
http://false.com<nil>
注意: Go 1.11 中添加了使用赋值修改模板变量,因此您需要使用 Go 1.11 或更新版本构建您的应用程序。如果您使用的是旧版本,则无法修改模板变量的值。
编辑: 我发现了一个副本:
你可以模仿早期版本的"changeable template variables",例子见这个问题: