英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论