-
Notifications
You must be signed in to change notification settings - Fork 17.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
text/template: index should return nil instead of index out of range error #14751
Comments
This is a huge pain indeed!
Edit: one off error, just further proves the point. |
The current behavior matches Go itself: a map lookup for a missing key returns a zero value; a slice lookup for an invalid index panics. I don't see a strong argument for diverging from the language here. Does the template package replace panics with nils in other cases? Also, the test is not that hard. Instead of:
you write:
Eliminating the panic will no doubt break other templates. This seems OK as is. /cc @robpike in case he disagrees. |
@rsc I don't buy your argument that "the current behavior matches Go itself". The signature for index(item interface{}, indices ...interface{}) (interface{}, error) It is a helper func full of reflection to make it usable in many situations ( You cannot write: {{if lt 0 (len .B)}}{{index .B .C}}{{else}}Not Found{{end}} Without knowing that
|
What I mean is that You are arguing that
|
There are plenty of cases where the template package avoids panics, which is a more relevant question: if idx < 0 || idx + 1 > len(s) {
return nil // avoid panic!
} But it is up to you. The workaround for people in the wild is to maintain |
@bep, please point to specific instances. I can't find the code snippet you posted in the text/template package nor the html/template package. In fact I can't find the string 'idx' in either of those at all. |
@rsc it was just a general remark -- as I assume that |
Please answer these questions before submitting your issue. Thanks!
go version
)?go env
)?I understand why I get this error and I expect arguments ala "you can fix this by doing proper length checking of the slice. Or you can provide your own implementation of the index template func".
Sure. But it isn't always obvious in a template if I interact with a
map
or aslice
, and with DRY in mind, I would say that range checking should be done in one place: Inside theindex
template func.And the answer to the question "is this really a problem?":
I'm one of the maintainers in Hugo, probably the project with the largest amount of end-user-provided Go templates, and the number one most frequent support question by a large margin, is: "How do I access that parameter/argument/data in a safe way?"
gohugoio/hugo#1949
The text was updated successfully, but these errors were encountered: