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 }}
1
  • 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. Apr 13, 2018 at 12:42

3 Answers 3

19

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

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

2

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)

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.