所以我正在做一个简单的 if 检查来自结构的 bool 值,但它似乎不起作用,它只是停止呈现 HTML。
所以下面的结构是这样的:
type Category struct {
ImageURL string
Title string
Description string
isOrientRight bool
}
现在我有一个类别结构的片段,我可以用一个范围来显示它。
下面是一个结构的例子:
juiceCategory := Category{
ImageURL: "lemon.png",
Title: "Juices and Mixes",
Description: `Explore our wide assortment of juices and mixes expected by
today's lemonade stand clientelle. Now featuring a full line of
organic juices that are guaranteed to be obtained from trees that
have never been treated with pesticides or artificial
fertilizers.`,
isOrientRight: true,
}
我尝试了多种方法,如下所示,但都没有用:
{{range .Categories}}
{{if .isOrientRight}}
Hello
{{end}}
{{if eq .isOrientRight true}}
Hello
{{end}}
<!-- Print nothing -->
{{ printf .isOrientRight }}
{{end}}
最佳答案
你必须导出所有你想从模板访问的字段:将它的第一个字母改为大写 I
:
type Category struct {
ImageURL string
Title string
Description string
IsOrientRight bool
}
以及对它的每一次引用:
{{range .Categories}}
{{if .IsOrientRight}}
Hello
{{end}}
{{if eq .IsOrientRight true}}
Hello
{{end}}
<!-- Print nothing -->
{{ printf .IsOrientRight }}
{{end}}
每个未导出的字段只能从声明包中访问。您的包声明了 Category
类型,并且 text/template
和 html/template
是不同的包,因此如果您希望这些包能够访问它,则需要将其导出。
Template.Execute()
返回一个错误,如果你已经存储/检查它的返回值,你会立即发现这一点,因为你会得到一个类似于这个的错误:
template: :2:9: executing "" at <.isOrientRight>: isOrientRight is an unexported field of struct type main.Category
在 Go Playground 上查看您的代码的工作示例.
关于go - 简单如果不工作 go 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44947119/