登录
首页 >  Golang >  Go问答

防止 Golang 模板中非 nil 值触发 if nil 块

来源:stackoverflow

时间:2024-03-11 17:51:28 216浏览 收藏

珍惜时间,勤奋学习!今天给大家带来《防止 Golang 模板中非 nil 值触发 if nil 块》,正文内容主要涉及到等等,如果你正在学习Golang,或者是对Golang有疑问,欢迎大家关注我!后面我会持续更新相关内容的,希望都能帮到正在学习的大家!

问题内容

以下内容错误地将 0 的值显示为“null”,但我只希望它对 nil 执行此操作。

package main

import (
    "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

如何让它显示 0 的值?

.value 是一个 interface{},在问题案例中包含 int,但可以包含任何内容。

如果对象为零,则在模板中显示默认内容,否则根据设置的属性显示接近但不完全相同的内容


解决方案


我只是创建一个使用 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

好了,本文到此结束,带大家了解了《防止 Golang 模板中非 nil 值触发 if nil 块》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>