Question: How can I do a different action if it is the last iteration of a loop #1753
-
This is less of an issue but more of a question port_mappings:
- test1:
container_port: 8080
protocol: "tcp"
app_protocol: "http2"
- test2:
container_port: 9090
protocol: "udp"
app_protocol: "http" This is passed into a template :
I want the last iteration not to add the "," so the rendered template is a valid json array like : "portMappings": [
{
"containerPort": 8080,
"protocol": "tcp",
"appProtocol": "http2"
},
{
"containerPort": 9090,
"protocol": "udp",
"appProtocol": "http"
}
], In other templating options there is built in $last signal that one can use. I can not find this type of option on how to do this. Thanks for the all the incredible work on the tool. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
@loque1 in that case, I've converted the issue to a discussion 😉 When ranging through
(this is kind of like That solves the comma after the
So, a kind of hacky way to detect whether you're on the last element could be to iterate through the map twice, setting a
Hope that makes sense! I'll bet there are simpler ways to approach this, however 😉 |
Beta Was this translation helpful? Give feedback.
@loque1 in that case, I've converted the issue to a discussion 😉
When ranging through
.config.port_mappings
, because it's an array,$key
is actually the index. You might be able to use thelen
builtin to find out if you're on the last element... Something like:(this is kind of like
if index != len(port_mappings) - 1 { printf(",") }
)That solves the comma after the
[]
, but for the map it's a bit more complex - one property of Go templates (and hence, gomplate) that's different from Go is that map keys are ordered naturally during iteration: