-
Notifications
You must be signed in to change notification settings - Fork 18.8k
Closed as not planned
Closed as not planned
Copy link
Labels
Milestone
Description
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)
}
}