I have a template that can optionally be prefixed with some string prefix. This prefix itself does not end with a newline character but can optionally contain newline characters (e.g. hello world
, hello\nworld
, ...). In the template, the newline is added and then the contents are rendered. If the prefix is the empty string, the rendered template immediately starts with the contents:
{{- with $.Prefix -}}
{{ . }}
{{ end -}}
Contents
Examples of what I want to achieve:
Prefix="Hello World"
:
Hello World
Contents
Prefix="Hello\nWorld
:
Hello
World
Contents
Prefix=""
:
Contents
However, due to the trailing hyphen in {{ end -}}
, when the prefix is set it renders as:
Hello WorldContents
But moving the hyphen to the start {{- end }}
fails to render the template when the prefix is not set:
Contents
My interpretation of how the hyphens should be executed is that the leading hyphen removes whitespace before the pipeline contents and vice-versa for after but somehow the newline contained in the $.Prefix block is removed by the trailing hyphen. How should I correct this?
I have a template that can optionally be prefixed with some string prefix. This prefix itself does not end with a newline character but can optionally contain newline characters (e.g. hello world
, hello\nworld
, ...). In the template, the newline is added and then the contents are rendered. If the prefix is the empty string, the rendered template immediately starts with the contents:
{{- with $.Prefix -}}
{{ . }}
{{ end -}}
Contents
Examples of what I want to achieve:
Prefix="Hello World"
:
Hello World
Contents
Prefix="Hello\nWorld
:
Hello
World
Contents
Prefix=""
:
Contents
However, due to the trailing hyphen in {{ end -}}
, when the prefix is set it renders as:
Hello WorldContents
But moving the hyphen to the start {{- end }}
fails to render the template when the prefix is not set:
Contents
My interpretation of how the hyphens should be executed is that the leading hyphen removes whitespace before the pipeline contents and vice-versa for after but somehow the newline contained in the $.Prefix block is removed by the trailing hyphen. How should I correct this?
Share Improve this question asked Nov 28, 2024 at 9:50 EmptylessEmptyless 3,0514 gold badges22 silver badges30 bronze badges 2 |1 Answer
Reset to default 0As the commenters (Cerise, Arkadiusz) pointed out, the example works and the issue was caused elsewhere by it being rendered as a nested template in a (complex) set of other template(s) which itself had incorrect hyphens. Rendering it before posting in the playground would have caught the wrong conclusion being drawn from the outputs of the tests.
Leaving this question up for others working with go-templates.
$.Prefix
is not empty do you want to include a newline. No single template formatting is going to take care of both those cases. – erik258 Commented Nov 28, 2024 at 14:12