问题是,text/template
中列出的第一个示例程序构建了一个套用信函。
虽然字母用范围解析,为什么.Gift
需要通过
{{with .Gift}} ..... {{.}} {{end}}
.Name
和.Attended
被直接处理。为什么?
因为Gift
是可选的,如果没有提供Gift
,我们不想感谢信中的任何内容;但如果提供Gift
,我们要感谢礼物。
仅当传递的管道不为空时,{{with}}
操作才会有条件地执行其主体:
{{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.
所以这个例子包含了这个:
{{with .Gift -}}
Thank you for the lovely {{.}}.
{{end}}
这意味着如果.Gift
不为空,则在输出(字母)中包含“谢谢”句子。如果.Gift
为空,则“谢谢”将被省略。