go - 简单如果不工作 go 模板

标签 go struct go-templates go-html-template

所以我正在做一个简单的 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/templatehtml/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/

相关文章:

Golang 模板不会加载

go - 如何使用 GORM 创建或更新记录?

go - 如何有效地在 golang 中存储对文件的 html 响应

linux - Golang 休息 api 和 curl

methods - 为什么我必须在 Rust 的结构之外声明方法?

go - 获取 Firestore 文档的值

go - 如何遍历文件但跳过一个特定的文件名

go - 将图像从 url 保存到文件

c++ - C++ 中的结构和类

C编程: Dereferencing pointer to incomplete type error