亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

簡單,如果不工作去模板

簡單,如果不工作去模板

Go
夢里花落0921 2022-04-20 17:27:00
所以我正在做一個簡單的 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}}
查看完整描述

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上查看您的代碼的工作示例。


查看完整回答
反對 回復 2022-04-20
?
郎朗坤

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,

}

現在無需更改您的模板...


查看完整回答
反對 回復 2022-04-20
  • 2 回答
  • 0 關注
  • 122 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號