How to split a long Go template function across multiple lines?
Asked Answered
P

3

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 }}
Photoplay answered 13/4, 2018 at 12:23 Comment(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.Plectognath
C
19

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

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

Clef answered 13/4, 2018 at 12:27 Comment(0)
R
3

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)

Rosellaroselle answered 18/2, 2023 at 19:51 Comment(0)
S
0

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

Sudbury answered 5/7, 2020 at 16:26 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.