Golang的text/Templates和{{with }} {{end}}的使用

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

Golang text/Templates and the use of {{with }} {{end}}

问题

问题是这样的,在text/template中列出的第一个示例程序构建了一封表单信。

虽然信件是通过Range解析的,但为什么需要通过.Gift使用?

.Name.Attended直接被引用了。为什么?

英文:

The question is this that the first example program listed in text/template
builds a form letter.

While the letter is parsed with a Range, why does .Gift need to be used via the

{{with .Gift}} ..... {{.}}  {{end}}

.Name and .Attended were directly addressed. Why?

答案1

得分: 2

因为“Gift”是可选的,如果没有提供“Gift”,我们不想在信中感谢任何东西;但是如果提供了“Gift”,我们想要感谢礼物。

“{{with}}”操作根据条件执行其主体,仅当传递的管道不为空时才执行:

{{with pipeline}} T1 {{end}}
如果管道的值为空,则不生成输出;
否则,dot被设置为管道的值,并执行T1。

所以示例中包含了这个:

{{with .Gift -}}
谢谢你送的可爱的{{.}}。
{{end}}

这意味着如果“.Gift”不为空,则在输出(信件)中包含“谢谢”句子。如果“.Gift”为空,则“谢谢”将被省略。

英文:

Because the Gift is optional, and if no Gift is provided, we don't want to thank for anything in the letter; but if Gift is provided, we want to say thanks for the gift.

The {{with}} action executes its body conditionally, only if the passed pipeline is not empty:

{{with pipeline}} T1 {{end}}
	If the value of the pipeline is empty, no output is generated;
	otherwise, dot is set to the value of the pipeline and T1 is
	executed.

So the example contains this:

{{with .Gift -}}
Thank you for the lovely {{.}}.
{{end}}

This means that if .Gift is not empty, then include the "thank you" sentence in the output (letter). If .Gift is empty, the "thank you" will be omitted.

huangapple
  • 本文由 发表于 2016年4月27日 16:00:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/36883780.html
匿名

发表评论

匿名网友

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

确定