英文:
Can I use a template variable in another template in Golang?
问题
模板 1
{{define "one"}}
{{ $var := "你好"}}
{{end}}
模板 2
{{define "two"}}
{{template "one"}}
说, {{print $var}}
{{end}}
我知道上面的例子是无效的。但是有没有办法在“two”模板中使用“one”模板的变量?
英文:
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
得分: 0
从阅读所有文档来看,答案似乎是否定的。当一个模板在嵌入到另一个模板之前被执行时,那个变量就不存在了,如果它的值在模板中被使用,它会显示为静态文本。
在模板_one_的示例中,$var
没有在任何地方使用,所以它被丢弃了。
执行顺序如下:
- 加载两个模板。
- 执行模板_one_,因为它没有被使用,所以
$var
被丢弃。 - 执行模板_two_,将模板_one_的结果嵌入其中。
如果这个解释是错误的,请评论或编辑它。
但是对于我的问题,标准模板库不会在模板之间传递模板变量。它们只用于局部使用。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论