【问题标题】:Simple if not working go template简单,如果不工作去模板
【发布时间】:2016-11-08 19:21:02
【问题描述】:

所以我正在对结构中的布尔值进行简单的 if 检查,但它似乎不起作用,它只是停止呈现 HTML。

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

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

现在我有了一个 Category 结构的切片,我可以用一个范围来显示它。

下面是一个结构的示例:

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

【问题讨论】:

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


    【解决方案1】:

    您必须从模板中导出所有要访问的字段:将其首字母更改为大写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: 在 <.isorientright> 处执行 "": isOrientRight 是结构类型 main.Category 的未导出字段

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

    【讨论】:

    • 哦,哇,非常感谢,这很有效。
    • 我不明白。
    【解决方案2】:

    如果生活对你施加了模板,这些模板由于某种原因具有小写变量名 - 可能是从 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,
    }
    

    现在无需更改模板...

    【讨论】:

      猜你喜欢
      • 2015-03-14
      • 2011-12-15
      • 2014-01-21
      • 2011-04-25
      • 1970-01-01
      • 1970-01-01
      • 2021-01-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多