Golang文本/模板以及{{with}} {{end}}的使用

问题描述 投票:2回答:1

问题是,text/template中列出的第一个示例程序构建了一个套用信函。

虽然字母用范围解析,为什么.Gift需要通过

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

.Name.Attended被直接处理。为什么?

templates go go-templates
1个回答
2
投票

因为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为空,则“谢谢”将被省略。

© www.soinside.com 2019 - 2024. All rights reserved.