Ste*_*eve 5 struct go go-templates go-html-template
所以我正在做一个简单的 if 检查来自结构的 bool 但它似乎不起作用,它只是停止呈现 HTML。
所以下面的结构是这样的:
type Category struct {
ImageURL string
Title string
Description string
isOrientRight bool
}
Run Code Online (Sandbox Code Playgroud)
现在我有一个 Category 结构的切片,我可以用一个范围来显示它。
Bellow 是一个结构体的示例:
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,
}
Run Code Online (Sandbox Code Playgroud)
我尝试了多种方法,如下所示,但都没有奏效:
{{range .Categories}}
{{if .isOrientRight}}
Hello
{{end}}
{{if eq .isOrientRight true}}
Hello
{{end}}
<!-- Print nothing -->
{{ printf .isOrientRight }}
{{end}}
Run Code Online (Sandbox Code Playgroud)
您必须从模板中导出要访问的所有字段:将其第一个字母更改为大写I:
type Category struct {
ImageURL string
Title string
Description string
IsOrientRight bool
}
Run Code Online (Sandbox Code Playgroud)
以及对它的每次引用:
{{range .Categories}}
{{if .IsOrientRight}}
Hello
{{end}}
{{if eq .IsOrientRight true}}
Hello
{{end}}
<!-- Print nothing -->
{{ printf .IsOrientRight }}
{{end}}
Run Code Online (Sandbox Code Playgroud)
每个未导出的字段只能从声明包中访问。您的包声明了Category类型,并且text/template和html/template是不同的包,因此如果您希望这些包能够访问它,则需要导出它。
Template.Execute() 返回一个错误,如果您已经存储/检查了它的返回值,您会立即发现这一点,因为您会收到与此类似的错误:
模板: :2:9: 在 <.isOrientRight> 处执行 "": isOrientRight 是结构类型 main.Category 的未导出字段
在Go Playground上查看代码的工作示例。
| 归档时间: |
|
| 查看次数: |
3335 次 |
| 最近记录: |