假设在应用模板之前,您有一个类似{ "Fruit": "apple" }的JSON值作为输入.我想判断"Fruit"的值是否在[]string{"pear", "banana", "grape"}的集合中,并根据值是否在集合中来做某事.

因此,输入到模板:

{ "fruit": "apple" }

模板(假设containsVal是一个自定义函数,我们将其传递给接受字符串和字符串片段的模板):

{{ if containsVal .Fruit []string{"banana", "grape", "etc"} }}do stuff{{ end }}

模板中似乎不允许使用字符串切片文字——模板无法编译.

显然,您可以定义一个 struct 并将其传递到.Execute().或者我可以在containsVal函数中硬编码我的值.

But for my purpose, I want the values to be dynamic and in the template, not hard-coded in Go code. So someone else should be able to come along and have a different set of values to check against ("fig", "cherry", etc.) by updating the template text.

我已经戳了大约https://pkg.go.dev/text/template和谷歌,并没有看到任何方法来做到这一点.我只能对更简单的变量进行简单的等式运算,比如模板中的string==string.

谢谢

推荐答案

您应该将"if"语句与"or"和"eq"运算符一起使用,如:

    tmplText := `
    {{ if eq .Fruit "banana" "grape" "etc" }}
        {{ .Fruit }} exists in the list
    {{ else }}
        {{ .Fruit }} doesn't exist in the list
    {{ end }}
`

    tmpl, err := template.New("").Parse(tmplText)
    if err != nil {
        panic(err)
    }

    err = tmpl.Execute(os.Stdout, map[string]interface{}{
        "Fruit": "apple",
    })
    if err != nil {
        panic(err)
    }

Go相关问答推荐

Go PQ驱动程序无法使用默认架构进行查询

如何在Golang中覆盖404

go mod tidy会自动升级go.mod中的go版本吗?

如何在golang中使用viper获取对象的配置数组?

如何在正则表达式中使整个单词可选?

为什么 mux.Vars() 返回空的 map[]

Golang 发送Post请求出现400错误

将文本文件放入切片然后进行比较

上传图片失败,出现错误dial tcp: lookup api.cloudinary.com: no such host

如何判断范围内的字段?

Apache Beam 在 Go 中从 PCollection 中 Select 前 N 行

CBC Decrypter 解密加密文本,但部分文本被随机字符替换

如何使用 go-playground/validator 编写 snake case 绑定标签?

为超时的单元测试创​​建 deadlineExceededError:true

将shell输出绑定到Go中的 struct 的最佳方法?

如何使用 math/big 对 bigInt 进行取模?

如何在眼镜蛇(golang)中将标志作为参数传递?

如何在 Go 中使用 Pact 返回错误请求(400、500)?

为什么在 unsafe.Sizeof() 中取消引用 nil 指针不会导致panic ?

Go 错误处理、类型断言和 net package包