In Go's html/template and text/template packages, the behavior for a "key not existing" (or a field not existing on a struct passed as data) depends on the context and the Go version.
Let's break down the default behavior and then how to "check" for these problems.
Default Behavior Explained
Missing Field on a Struct (Compile-Time Error):
If you pass a struct to the template and try to access a field that does not exist on that struct, it's typically a parse-time error. This means your template.Parse() or template.Must() call will fail. This is good, as it catches errors early.
go
type Data struct {
Name string
}
tmpl, err := template.New("test").Parse("Hello, {{.Name}} and {{.NonExistentField}}!")
// This Parse call will return an error:
// template: test:1:21: executing "test" at <.NonExistentField>: can't evaluate field NonExistentField in type main.Data
Missing Key in a Map (Runtime - Defaults to Zero Value/Empty String):
If you pass a map[string]interface{} (or similar map type) to the template and try to access a key that does not exist in that map, the template engine will NOT return an error by default. Instead, it will render the zero value for the expected type, which is an empty string for string contexts.
go
// In Go Code
data := map[string]string{
"Name": "Alice",
}
tmpl, err := template.New("test").Parse("Hello, {{.Name}} and {{.Age}}!")
if err != nil {
log.Fatal(err)
}
var buf bytes.Buffer
err = tmpl.Execute(&buf, data)
if err != nil {
log.Fatal(err)
}
fmt.Println(buf.String())
// Output: Hello, Alice and ! (Notice the empty space for Age)
This default behavior for maps is often the "problem" people want to check for.
How to Check/Handle "Key Not Existing" Problems
There are several strategies, from strict erroring to graceful handling.
1. missingkey=error Option (Go 1.14+) - Recommended for Strict Checking
This is the most direct way to get an error when a map key or struct field is missing (and would otherwise render its zero value).
You apply this option when parsing your template:
go
package main
import (
"bytes"
"fmt"
"html/template" // or "text/template"
"log"
)
func main() {
data := map[string]string{
"Name": "Alice",
}
// Option 1: Using template.Parse with Option()
tmpl, err := template.New("test").Option("missingkey=error").Parse("Hello, {{.Name}} and {{.Age}}!")
if err != nil {
log.Fatal(err) // This will NOT error here, as it's a runtime check
}
var buf bytes.Buffer
err = tmpl.Execute(&buf, data)
if err != nil {
// This is where the error for missing .Age will occur
fmt.Printf("Render error: %v\n", err)
// Example output: Render error: html/template: "test" is an incomplete or empty template:
// html/template: "test" (html/template:1:21): executing "test" at <.Age>: map has no entry for key "Age"
} else {
fmt.Println(buf.String())
}
fmt.Println("\n--- Example with struct (no error as field missing is parse error) ---")
type Person struct {
Name string
}
personData := Person{Name: "Bob"}
// Note: missingkey=error affects *runtime* missing keys/fields.
// A non-existent field on a struct is a *parse-time* error.
tmpl2, err := template.New("test2").Option("missingkey=error").Parse("Hi, {{.Name}} and {{.City}}!")
if err != nil {
fmt.Printf("Parse error for struct: %v\n", err) // This will error here!
// Output: Parse error for struct: template: test2:1:19: executing "test2" at <.City>: can't evaluate field City in type main.Person
}
}
How missingkey=error works:
missingkey=zero (default): Missing map keys and struct fields will render as their zero value (e.g., empty string, 0, false).
missingkey=error: Missing map keys and struct fields will cause an error during Execute().
missingkey=default: Similar to zero, but only for fields that could have a default (less common).
2. Using if or with in the Template - For Optional Data
If a key's absence is not an error but simply means the data isn't available, you can check for its existence (or non-zero value) directly in the template.
go
package main
import (
"bytes"
"fmt"
"html/template"
"log"
)
func main() {
data := map[string]string{
"Name": "Alice",
// "Age" is intentionally missing
}
tmpl, err := template.New("test").Parse(`
Hello, {{.Name}}!
{{if .Age}}Your age is {{.Age}}.{{else}}Age not provided.{{end}}
{{with .City}}You live in {{.}}.{{else}}City not provided.{{end}}
`)
if err != nil {
log.Fatal(err)
}
var buf bytes.Buffer
err = tmpl.Execute(&buf, data)
if err != nil {
log.Fatal(err)
}
fmt.Println(buf.String())
/* Output:
Hello, Alice!
Age not provided.
City not provided.
*/
}
{{if .Key}}: Checks if Key is "truthy" (non-zero, non-empty string, non-nil, non-empty slice/map). If the key is missing from a map, it evaluates to its zero value, which is "falsy", so the else block is executed.
{{with .Key}}: Changes the current dot . to the value of Key. If Key is "falsy" (e.g., missing map key), the else block is executed, and . remains unchanged or goes back to the parent context.
3. Pre-processing Data in Go Code
Before passing data to the template, you can validate or enrich it in your Go code. This is useful if you need to perform complex checks or fetch defaults.
go
package main
import (
"bytes"
"fmt"
"html/template"
"log"
)
type UserData struct {
Name string
Age int
City string
IsValid bool
}
func main() {
rawInput := map[string]interface{}{
"Name": "Alice",
// "Age" is missing, "City" is missing
}
// Pre-process and validate data
processedData := UserData{
Name: "Unknown", // Default
Age: 0, // Default
City: "N/A", // Default
IsValid: true,
}
if name, ok := rawInput["Name"].(string); ok && name != "" {
processedData.Name = name
} else {
processedData.IsValid = false
log.Println("Warning: Name is missing or invalid")
}
if age, ok := rawInput["Age"].(int); ok && age > 0 {
processedData.Age = age
} else {
// processedData.Age remains 0, or set a specific default
}
if city, ok := rawInput["City"].(string); ok && city != "" {
processedData.City = city
}
if !processedData.IsValid {
log.Println("Error: User data is incomplete.")
// You might return an error here, or render a different template
}
tmpl, err := template.New("user").Parse(`
User: {{.Name}}
Age: {{.Age}}
City: {{.City}}
Validation Status: {{if .IsValid}}Valid{{else}}Invalid{{end}}
`)
if err != nil {
log.Fatal(err)
}
var buf bytes.Buffer
err = tmpl.Execute(&buf, processedData)
if err != nil {
log.Fatal(err)
}
fmt.Println(buf.String())
/* Output:
User: Alice
Age: 0
City: N/A
Validation Status: Valid
*/
}
4. Custom Template Functions
You can define a custom function that you pass to the template, which checks for a key's existence and returns an error or a default value.
go
package main
import (
"bytes"
"fmt"
"html/template"
"log"
"strings"
)
// mustGet returns the value for key or an error if not found.
func mustGet(data interface{}, key string) (interface{}, error) {
if m, ok := data.(map[string]interface{}); ok {
if val, exists := m[key]; exists {
return val, nil
}
}
if m, ok := data.(map[string]string); ok { // Handle map[string]string specifically
if val, exists := m[key]; exists {
return val, nil
}
}
// Add more type assertions as needed (e.g., reflect for structs)
return nil, fmt.Errorf("key '%s' not found", key)
}
func main() {
data := map[string]string{
"Name": "Alice",
}
tmpl := template.New("test")
tmpl.Funcs(template.FuncMap{
"get": mustGet,
})
_, err := tmpl.Parse(`
Hello, {{.Name}}!
Age: {{ (get . "Age") }}
City: {{ (get . "City") }}
`)
if err != nil {
log.Fatal(err)
}
var buf bytes.Buffer
err = tmpl.Execute(&buf, data)
if err != nil {
// This is where the error from mustGet will appear
fmt.Printf("Render error: %v\n", err)
// Example output: Render error: html/template: "test" (html/template:4:11): executing "test" at <(get . "Age")>: error calling get: key 'Age' not found
} else {
fmt.Println(buf.String())
}
// Example with handling the error in template (more complex)
tmpl2 := template.New("test2")
tmpl2.Funcs(template.FuncMap{
"getOrDefault": func(data interface{}, key, defaultValue string) string {
if m, ok := data.(map[string]interface{}); ok {
if val, exists := m[key]; exists {
if s, ok := val.(string); ok {
return s
}
}
}
if m, ok := data.(map[string]string); ok {
if val, exists := m[key]; exists {
return val
}
}
return defaultValue
},
})
_, err = tmpl2.Parse(`
Name: {{.Name}}
Age: {{ getOrDefault . "Age" "Not provided" }}
City: {{ getOrDefault . "City" "Unknown" }}
`)
if err != nil {
log.Fatal(err)
}
buf.Reset()
err = tmpl2.Execute(&buf, data)
if err != nil {
log.Fatal(err)
}
fmt.Println(strings.TrimSpace(buf.String()))
/* Output:
Name: Alice
Age: Not provided
City: Unknown
*/
}
Which Strategy to Choose?
missingkey=error (Go 1.14+):
Use when: A missing key/field genuinely indicates a problem or bug in your data preparation that should halt rendering. This is the closest to throwing an error like other templating engines.
Cons: Requires Go 1.14+. Might be too strict if you have many optional fields.
{{if .Key}} / {{with .Key}} in Template:
Use when: A key is genuinely optional and its absence should lead to different content or nothing at all, not an error.
Pros: Clean, idiomatic template code. Template controls its own rendering logic.
Cons: Doesn't propagate an "error" to your Go code. Makes it harder to distinguish between an intentionally missing optional field and an accidental omission.
Pre-processing Data in Go Code:
Use when: You need complex validation, default values, or transformations of data before rendering. Also good if the "missing key" problem needs to be handled programmatically (e.g., logging, redirecting, sending specific HTTP responses).
Pros: Centralized logic, full control in Go.
Cons: Can lead to verbose Go code if you have many fields.
Custom Template Functions:
Use when: You want specific, reusable logic for handling missing values directly within the template, beyond what if/with provides (e.g., returning an error, or a formatted default).
Pros: Encapsulates complex logic.
Cons: Can make templates less readable if functions are obscure. Error handling from functions within templates can be tricky to manage gracefully.
For directly checking "template render problem of key not existing," the tmpl.Option("missingkey=error") is your best bet as it forces an error specifically for this condition. For gracefully handling optional data, {{if .Key}} is the standard.