Tedious if Operation with Go Template
In an attempt to perform a conditional check in a Go template, you may encounter unexpected issues. Consider the following scenario:
You have declared a struct called Category with a bool field named isOrientRight. Within a range loop iterating over a slice of Category structs, you attempt to use {{if}} statements to control the output based on the value of isOrientRight. However, the template only displays an empty page.
The Solution
To resolve this problem, you need to export the fields of the Category struct by capitalizing their first letters. By default, unexported fields (starting with lowercase letters) can only be accessed within the package that declares the type. In this case, text/template and html/template are separate packages, so you need to export the fields to allow them access.
Here's the updated code:
type Category struct { ImageURL string
The above is the detailed content of Why is my Go Template not Evaluating Conditionals with Unexported Fields?. For more information, please follow other related articles on the PHP Chinese website!