Godfather
Godfather

Reputation: 179

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

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?

Upvotes: 2

Views: 1313

Answers (1)

icza
icza

Reputation: 418535

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.

Upvotes: 2

Related Questions