以下錯誤地為 的值顯示“null” 0,但我只希望它完全對 執行此操作nil。package mainimport ( "os" "text/template")type thing struct { Value interface{}}func main() { tmpl, _ := template.New("test").Parse("{{if .Value }} {{.Value}} {{else}} [null] {{end}}\n") tmpl.Execute(os.Stdout, thing{Value: "hi"}) // outputs hi tmpl.Execute(os.Stdout, thing{Value: nil}) // outputs [null] tmpl.Execute(os.Stdout, thing{Value: 0}) // outputs [null] - should output 0 tmpl.Execute(os.Stdout, thing{Value: 2}) // outputs 2}游樂場鏈接:https://play.golang.org/p/Gg8uBCOb2vE我如何讓它顯示0instead 的價值?.Value是一個interface{}在問題案例中包含一個int,但可以包含任何內容。如果對象為 nil,則在模板中顯示默認內容;否則,根據設置的屬性顯示接近但不完全相同的內容
1 回答

素胚勾勒不出你
TA貢獻1827條經驗 獲得超9個贊
我只想創建一個函數,您使用以下方法傳遞給模板template.Funcs:
https://play.golang.org/p/anxW5ooGE7N
funcs := make(map[string]interface{})
funcs["isNotNull"] = func(t interface{}) bool {
return t != nil
}
tmpl, _ := template.New("test").Funcs(funcs).Parse("{{if isNotNull .Value }} {{.Value}} {{else}}[null] {{end}}\n")
tmpl.Execute(os.Stdout, thing{Value: "hi"}) // outputs hi
tmpl.Execute(os.Stdout, thing{Value: nil}) // outputs [null]
tmpl.Execute(os.Stdout, thing{Value: 0}) // outputs 0
tmpl.Execute(os.Stdout, thing{Value: 2}) // outputs 2
- 1 回答
- 0 關注
- 140 瀏覽
添加回答
舉報
0/150
提交
取消