Skip to content

proposal: text/template: Throw an error on missing variable while parsing the template #60073

@droslean

Description

@droslean

Currently the text/template package forces the user to use maps in order to force an error on missing variables.

missingkey=error option works only when trying to parse a template string by passing a map of values.

With this issue, I am proposing to add a new option for empty or missing variables in the struct that is given as input to parse the template.

Working example using a map:

package main

import (
	"bytes"
	"text/template"
)

func main() {
	data := map[string]interface{}{
		"TestVar1": "test-1",
		"TestVar2": "test-2",
	}

	inputText := "{{.TestVar1}} {{.TestVar2}} {{.TestVar3}}"
	t, err := template.New("input").Parse(inputText)
	if err != nil {
		panic(err)
	}

	var buff []byte
	outputBuffer := bytes.NewBuffer(buff)

	if err := t.Option("missingkey=error").Execute(outputBuffer, data); err != nil {
		panic(err)
	}
}

Non-working example using a struct:

package main

import (
	"bytes"
	"text/template"
)

type Data struct {
	TestVar1 string
	TestVar2 string
	TestVar3 string
}

func main() {
	data := Data{
		TestVar1: "test-1",
		TestVar2: "test-2",
	}

	inputText := "{{.TestVar1}} {{.TestVar2}} {{.TestVar3}}"
	t, err := template.New("input").Parse(inputText)
	if err != nil {
		panic(err)
	}

	var buff []byte
	outputBuffer := bytes.NewBuffer(buff)

	if err := t.Option("missingkey=error").Execute(outputBuffer, data); 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