为了账号安全,请及时绑定邮箱和手机立即绑定

有没有更好的方法可以检查模板属性是否未解析?

有没有更好的方法可以检查模板属性是否未解析?

Go
幕布斯7119047 2022-12-19 21:16:35
我正在尝试使用构建一个字符串text/template,其中模板字符串可以具有通过映射解析的任意属性。我想要完成的是确定一个/任何模板属性未解析的位置并返回错误。目前,我正在使用,regexp但正在接触社区,看看是否有更好的解决方案。package mainimport (    "bytes"    "fmt"    "regexp"    "text/template")func main() {    data := "teststring/{{.someData}}/{{.notExist}}/{{.another}}"    // the issue here is that data can be arbitrary so i cannot do    // a lot of unknown if statements    t := template.Must(template.New("").Parse(data))    var b bytes.Buffer    fillers := map[string]interface{}{        "someData": "123",        "another":  true,        // in this case, notExist is not defined, so the template will        // note resolve it    }    if err := t.Execute(&b, fillers); err != nil {        panic(err)    }    fmt.Println(b.String())    // teststring/123/<no value>/true    // here i am trying to catch if a the template required a value that was not provided    hasResolved := regexp.MustCompile(`<no value>`)    fmt.Println(hasResolved.MatchString(b.String()))    // add notExist to the fillers map    fillers["notExist"] = "testdata"    b.Reset()    if err := t.Execute(&b, fillers); err != nil {        panic(err)    }    fmt.Println(b.String())    fmt.Println(hasResolved.MatchString(b.String()))    // Output:    // teststring/123/<no value>/true    // true    // teststring/123/testdata/true    // false}
查看完整描述

1 回答

?
一只斗牛犬

TA贡献1784条经验 获得超2个赞

您可以通过设置模板上的选项让它失败:


func (t *Template) Option(opt ...string) *Template

"missingkey=default" or "missingkey=invalid"

    The default behavior: Do nothing and continue execution.

    If printed, the result of the index operation is the string

    "<no value>".

"missingkey=zero"

    The operation returns the zero value for the map type's element.

"missingkey=error"

    Execution stops immediately with an error.

如果你将它设置为missingkey=error,你会得到你想要的。


t = t.Options("missingkey=error")


查看完整回答
反对 回复 2022-12-19
  • 1 回答
  • 0 关注
  • 72 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信