假设在应用模板之前,您有一个类似{ "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.
谢谢