2 回答

TA貢獻1828條經驗 獲得超3個贊
您必須導出要從模板訪問的所有字段:將其第一個字母更改為大寫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/template并且html/template是不同的包,因此如果您希望這些包可以訪問它,則需要導出它。
Template.Execute()返回一個錯誤,如果您已經存儲/檢查了它的返回值,您會立即發現這一點,因為您會收到與此類似的錯誤:
模板::2:9:在 <.isOrientRight> 處執行“”:isOrientRight 是結構類型 main.Category 的未導出字段
在Go Playground上查看您的代碼的工作示例。

TA貢獻1921條經驗 獲得超9個贊
如果生活對您施加了模板,由于某種原因具有小寫變量名 - 可能是由 Pug 模板源構建的,也用于其他事情 - 有一種方法可以解決這個問題......
您可以使用 amap[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,
}
現在無需更改您的模板...
- 2 回答
- 0 關注
- 122 瀏覽
添加回答
舉報