我可以在Golang中的另一个模板中使用模板变量吗?
Template 1
{{define "one"}}
{{ $var := "Hello"}}
{{end}}
Template 2
{{define "two"}}
{{template "one"}}
Say, {{print $var}}
{{end}}
I know the above example isn't valid. But is there a way to use the variable of "one"
template into "two"
template?
模板1 p>
{{定义“一个”}}
{{$ var:=“ Hello”}}
{{end}}
code> pre>
模板2 p>
{{define“ two”}}
{{template“ one”}}
说,{{print $ var}}
{{end}}
code> pre> \ n
我知道上面的示例无效。 但是有办法将“一个” code>模板的变量用于“两个” code>模板吗? p>
div>
From reading all the documentation. The answer seems to be no. When a template is executed before being embedded into another, that variable is gone and if its value is used in the template, it appears as static text.
In the example of template one, $var
isn't used anywhere, so it is thrown away.
The order of execution would be.
- Load both templates.
- Template one is executed, throwing
$var
away because it wasn't used. - Template two is executed, embedding the result of template one in it.
If this explanation is incorrect. Please comment or edit it.
But the answer to my question is that the standard templating library doesn't pass template variables between templates. They are meant for local use.