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

我正在尝试使用构建一个字符串text/template,其中模板字符串可以具有通过映射解析的任意属性。


我想要完成的是确定一个/任何模板属性未解析的位置并返回错误。


目前,我正在使用,regexp但正在接触社区,看看是否有更好的解决方案。


package main


import (

    "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

}


幕布斯7119047
浏览 75回答 1
1回答

一只斗牛犬

您可以通过设置模板上的选项让它失败:func (t *Template) Option(opt ...string) *Template"missingkey=default" or "missingkey=invalid"&nbsp; &nbsp; The default behavior: Do nothing and continue execution.&nbsp; &nbsp; If printed, the result of the index operation is the string&nbsp; &nbsp; "<no value>"."missingkey=zero"&nbsp; &nbsp; The operation returns the zero value for the map type's element."missingkey=error"&nbsp; &nbsp; Execution stops immediately with an error.如果你将它设置为missingkey=error,你会得到你想要的。t = t.Options("missingkey=error")
打开App,查看更多内容
随时随地看视频慕课网APP