Skip to content

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

@WGH-

Description

@WGH-

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.

Metadata

Metadata

Assignees

Labels

NeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions