Skip to content

Question: How can I do a different action if it is the last iteration of a loop #1753

Answered by hairyhenderson
loque1 asked this question in Q&A
Discussion options

You must be logged in to vote

This is less of an issue but more of a question [...]

@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 the len builtin to find out if you're on the last element... Something like:

{{ if ne (sub (len .config.port_mappings) 1) $index }},{{end}}

(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:

If the value is a map and the…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@loque1
Comment options

Answer selected by loque1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants
Converted from issue

This discussion was converted from issue #1752 on May 31, 2023 00:08.