简单,如果不工作去模板

时间:2016-11-08 19:21:02

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

所以我做一个简单的操作,如果检查一个结构中的bool,但它似乎不起作用,它只是停止渲染HTML。

所以下面的结构是这样的:

type Category struct {
    ImageURL      string
    Title         string
    Description   string
    isOrientRight bool
}

现在我有一个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,
}

我尝试了多种方法,如下所示,但都没有效果:

{{range .Categories}}
    {{if .isOrientRight}}
       Hello
    {{end}}
    {{if eq .isOrientRight true}}
       Hello
    {{end}}

   <!-- Print nothing -->
   {{ printf .isOrientRight }} 

{{end}}

2 个答案:

答案 0 :(得分:4)

您必须从模板中导出您要访问的所有字段:将其第一个字母更改为大写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()会返回错误,如果你已经存储/检查了它的返回值,你会立即发现它,因为你得到的错误与此类似:

  

模板:: 2:9:执行&#34;&#34; at&lt; .isOrientRight&gt;:isOrientRight是struct类型main.Category的未导出字段

Go Playground上查看代码的工作示例。

答案 1 :(得分:1)

如果生活对你造成了模板,由于某些原因这些模板有小写的变量名 - 可能是从也用于其他事情的Pug模板源构建的 - 有一种解决这个问题的方法......

您可以使用map[string]interface{}来保存要传递到模板中的值,因此在上面的示例中:

juiceCategory := map[string]interface{}{
    "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,
}

现在无需更改模板......