Skip to content
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: missingkey does not affect builtin "index" function #60008

Open
WGH- opened this issue May 5, 2023 · 4 comments
Open

text/template: missingkey does not affect builtin "index" function #60008

WGH- opened this issue May 5, 2023 · 4 comments
Assignees
Labels
NeedsInvestigation Someone must examine and confirm this is a valid issue and not a duplicate of an existing one.
Milestone

Comments

@WGH-
Copy link

WGH- commented May 5, 2023

The documentation for the missingkey option says:

missingkey: Control the behavior during execution if a map is indexed with a key that is not present in the map.

It sounds like it might apply to index builtin function as well, but it applies only to the .X.Y.Z syntax.

https://go.dev/play/p/ZneXhxfIBWT

package main

import (
	"fmt"
	"io"
	"text/template"
)

func f(text string) {
	fmt.Println(text)
	t := template.Must(template.New("").Option("missingkey=error").Parse(text))
	err := t.Execute(io.Discard, map[string]any{})
	fmt.Println(err)
	fmt.Println()
}

func main() {
	f(`{{ .Foobar }}`)
	// template: :1:3: executing "" at <.Foobar>: map has no entry for key "Foobar"
	f(`{{ index . "Foobar" }}`)
	// <nil>
}

It's hard to say whether this is behavioural bug, or just an ambiguity in documentation. Although I have use cases where missingkey applying to index builtin would be preferrable (replacement for .X.Y.Z if map keys don't happen to be valid identifiers), this indeed would be inconsistent with index expression of Go language itself.

@seankhliao seankhliao added the NeedsInvestigation Someone must examine and confirm this is a valid issue and not a duplicate of an existing one. label May 5, 2023
@seankhliao seankhliao added this to the Unplanned milestone May 5, 2023
@seankhliao
Copy link
Member

cc @robpike

@robpike robpike self-assigned this May 11, 2023
@spdrcd
Copy link

spdrcd commented Nov 16, 2023

WGH- Thanks for posting this... I agree 👍 hope this could be resolved

@robpike
Copy link
Contributor

robpike commented Nov 16, 2023

Tricky. What should happen if you index a slice by -1?

@spdrcd
Copy link

spdrcd commented Nov 16, 2023

Tricky. What should happen if you index a slice by -1?

what does that question mean? lol 😄

  • right now no error is returned if slice is empty and it will fill with empty string

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
NeedsInvestigation Someone must examine and confirm this is a valid issue and not a duplicate of an existing one.
Projects
None yet
Development

No branches or pull requests

4 participants