简单,如果不工作去模板

所以我正在做一个简单的 if 检查结构中的布尔值,但它似乎不起作用,它只是停止渲染 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}}


梦里花落0921
浏览 102回答 2
2回答

倚天杖

您必须导出要从模板访问的所有字段:将其第一个字母更改为大写I:type Category struct {&nbsp; &nbsp; ImageURL&nbsp; &nbsp; &nbsp; string&nbsp; &nbsp; Title&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;string&nbsp; &nbsp; Description&nbsp; &nbsp;string&nbsp; &nbsp; IsOrientRight bool}以及对它的每一个引用:{{range .Categories}}&nbsp; &nbsp; {{if .IsOrientRight}}&nbsp; &nbsp; &nbsp; &nbsp;Hello&nbsp; &nbsp; {{end}}&nbsp; &nbsp; {{if eq .IsOrientRight true}}&nbsp; &nbsp; &nbsp; &nbsp;Hello&nbsp; &nbsp; {{end}}&nbsp; &nbsp;<!-- Print nothing -->&nbsp; &nbsp;{{ printf .IsOrientRight }}&nbsp;{{end}}每个未导出的字段只能从声明包中访问。您的包声明了Category类型,text/template并且html/template是不同的包,因此如果您希望这些包可以访问它,则需要导出它。Template.Execute()返回一个错误,如果您已经存储/检查了它的返回值,您会立即发现这一点,因为您会收到与此类似的错误:模板::2:9:在 <.isOrientRight> 处执行“”:isOrientRight 是结构类型 main.Category 的未导出字段在Go Playground上查看您的代码的工作示例。

郎朗坤

如果生活对您施加了模板,由于某种原因具有小写变量名 - 可能是由 Pug 模板源构建的,也用于其他事情 - 有一种方法可以解决这个问题......您可以使用 amap[string]interface{}来保存要传递到模板中的值,因此在上面的示例中:juiceCategory := map[string]interface{}{&nbsp; &nbsp; "ImageURL": "lemon.png",&nbsp; &nbsp; "Title":&nbsp; &nbsp; "Juices and Mixes",&nbsp; &nbsp; "Description": `Explore our wide assortment of juices and mixes expected by&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; today's lemonade stand clientelle. Now featuring a full line of&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; organic juices that are guaranteed to be obtained from trees that&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; have never been treated with pesticides or artificial&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fertilizers.`,&nbsp; &nbsp; "isOrientRight": true,}现在无需更改您的模板...
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go