donglanche9257 2016-11-08 19:21
浏览 19
已采纳

如果无法正常使用,则很简单

So I am doing a simple if check on a bool from a struct but it doesn't seem to work, it just stop rendering the HTML.

So the following struct is like this:

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

Now I have a slice of that Category struct which I get to display with a range.

Bellow is an example of one struct:

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,
}

I've tried multiple ways, like below, but none of them worked:

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

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

{{end}}
  • 写回答

2条回答 默认 最新

  • duanci9305 2016-11-08 19:42
    关注

    You have to export all the fields you want to access from templates: change its first letter to capital I:

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

    And every reference to it:

    {{range .Categories}}
        {{if .IsOrientRight}}
           Hello
        {{end}}
        {{if eq .IsOrientRight true}}
           Hello
        {{end}}
    
       <!-- Print nothing -->
       {{ printf .IsOrientRight }} 
    
    {{end}}
    

    Every unexported field can only be accessed from the declaring package. Your package declares the Category type, and text/template and html/template are different packages, so you need to export it if you want those packages to have access to it.

    Template.Execute() returns an error, should you have stored / examined its return value, you would have found this out immediately, as you'd get an error similar to this one:

    template: :2:9: executing "" at <.isOrientRight>: isOrientRight is an unexported field of struct type main.Category

    See a working example of your code on the Go Playground.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题