14

I have a very long printf call in a Go template. Example:

{{ printf "mongodb://%s:%s@%s/%s?authSource=admin&replicaSet=%s&readPreference=nearest&w=majority" .Values.rocketchat.mongo.username .Values.rocketchat.mongo.password .Values.rocketchat.mongo.database .Values.mongodb-replicaset.replicaSetName | b64enc | quote }}

How can I split this across multiple lines (like below)?

{{ printf "mongodb://%s:%s@%s/%s?authSource=admin&replicaSet=%s&readPreference=nearest&w=majority"
    .Values.rocketchat.mongo.username
    .Values.rocketchat.mongo.password
    .Values.rocketchat.mongo.database
    .Values.mongodb-replicaset.replicaSetName
    | b64enc | quote }}
allsap
  • 333
  • 3
  • 8
  • The only way to do that would be to change your function to take a composite type (such as a `struct` or `map`), then build that composite type line-by-line. But don't do that. Generally speaking, but doubly so in templates, if you feel your lines are too long, it means you need to refactor with a simplification. – Jonathan Hall Apr 13 '18 at 12:42

3 Answers3

19

This cannot be done. From the text/template documentation:

Except for raw strings, actions may not span newlines, although comments can.

1

For posterity, since Go 1.16 you can have template actions span more than one line; from the release notes:

Newlines characters are now allowed inside action delimiters, permitting actions to span multiple lines.

(example implementation)

Carrotman42
  • 1,744
  • 1
  • 14
  • 19
0

I think you need to use string literals instead, see some examples here: https://golang.org/src/html/template/example_test.go

Ariel Monaco
  • 3,695
  • 1
  • 23
  • 21