Match behaviour of "index" with "." if key does not exist #1545
Replies: 3 comments 4 replies
-
Hi @robinchrist, thanks for posting this. Indeed, this is the behaviour: $ gomplate -i '{{ .missing }}'
10:33:54 ERR error="failed to render template <arg>: template: <arg>:1:3: executing \"<arg>\" at <.missing>: map has no entry for key \"missing\""
$ gomplate -i '{{ index . "missing" }}'
<no value> I'm interested in a bit more clarity on this statement:
Why do you think To expand a bit on the background provided in #1362, this Go code can be considered equivalent to the two approaches: // ".foo" in a template
fmt.Printf("%v", myContext.foo)
// "index . `foo`" in a template
fmt.Printf("%v", myMap["foo"]) Assuming However, if All this to say - It's also worth mentioning that s := []int{1, 2, 3}
// equivalent to "index $s 4" in a template
fmt.Printf("%v", s[4]) This will panic with The equivalent gomplate template behaves the same: $ gomplate -i '{{ $a := slice 0 1 2 }}{{ index $a 4 }}'
10:48:13 ERR error="failed to render template <arg>: template: <arg>:1:26: executing \"<arg>\" at <index $a 5>: error calling index: index out of range: 4" As workarounds, as suggested in #1362, using |
Beta Was this translation helpful? Give feedback.
-
FYI I've issued #1588 to clarify the docs - @robinchrist if you're able would you mind having a look and letting me know if it's clear? |
Beta Was this translation helpful? Give feedback.
-
Also see #1589 |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
While accessing values via
.
throws an error if the requested key does not exist,index
does not and instead produces<no value>
in the output - this is somewhat surprising and not really consistent.I believe it would be a good thing to make both operators,
.
andindex
behave the same in this case, i.e. makeindex
throw an error if the requested key does not existThis could potentially be hidden behind a flag to make sure no legacy code breaks (as I can imagine that some people may rely on that behaviour)
Related issue: #1362
Beta Was this translation helpful? Give feedback.
All reactions