Skip to content

proposal: text/template: New template option additionalkey #57857

@drewgonzales360

Description

@drewgonzales360

👋 Hey folks, I'd like to add a new option when rendering templates that will error in the event that there are additional fields in the input. The original issue I'm trying to fix is in helm, so if anyone has an alternative solution to that, I'm open to it.

// Known options:
//
// missingkey: Control the behavior during execution if a map is
// indexed with a key that is not present in the map.
//
//	"missingkey=default" or "missingkey=invalid"
//		The default behavior: Do nothing and continue execution.
//		If printed, the result of the index operation is the string
//		"<no value>".
//	"missingkey=zero"
//		The operation returns the zero value for the map type's element.
//	"missingkey=error"
//		Execution stops immediately with an error.
//	"additionalkey=default"                                                      # New thing
//		Do nothing when additional keys are found.
//	"additionalkey=error"                                                        # New thing
//		Execution finishes with an error if a key is provided, but unused.

Then the following code (taken from the text/template example) would panic

package main

import (
	"html/template"
	"os"
)

type Inventory struct {
	Material   string
	Count      uint
	ExtraField string
}

func main() {
	sweaters := Inventory{"wool", 17, "unused field"}
	tmpl, err := template.New("test").Parse("{{.Count}} items are made of {{.Material}}")
	
	// Throw an error if extra fields are found. In this case ExtraField is unused.
	tmpl.Option("additionalkey=error")

	if err != nil {
		panic(err)
	}
	err = tmpl.Execute(os.Stdout, sweaters)
	if err != nil {
		panic(err)
	}
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions