在Golang中,可以在一个模板中使用另一个模板的变量吗?

huangapple go评论67阅读模式
英文:

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没有在任何地方使用,所以它被丢弃了。

执行顺序如下:

  1. 加载两个模板。
  2. 执行模板_one_,因为它没有被使用,所以$var被丢弃。
  3. 执行模板_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.

  1. Load both templates.
  2. Template one is executed, throwing $var away because it wasn't used.
  3. 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.

huangapple
  • 本文由 发表于 2016年3月8日 11:34:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/35858441.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定