我想知道是否可以,如果可以的话,如何测试一个值是否是 Go 模板中的字符串。
我尝试了以下方法,但没有成功
{{- range .Table.PrimaryKeys.DBNames.Sorted }}{{ with (index $colsByName .)}}
{{ .Name }}: {{ if .IsArray }}[]{{ end }}'{{.Type}}', {{end}}
{{- end }}
{{- range $nonPKDBNames }}{{ with (index $colsByName .) }}
{{ .Name }}: {{ if .IsArray }}[]{{end -}} {
type: {{ if .Type IsString}}GraphQLString{{end -}}, # line of interest where Type is a value that could be a number, string or an array
}, {{end}}
{{- end }}
这是我得到的错误
Error: error parsing TablePaths: error parsing contents template: template: templates/table.gotmpl:42: function "IsString" not defined
最佳答案
自定义函数
没有预先声明的IsString()
函数在模板中可用,但我们可以很容易地注册和使用这样的函数:
t := template.Must(template.New("").Funcs(template.FuncMap{
"IsString": func(i interface{}) bool {
_, ok := i.(string)
return ok
},
}).Parse(`{{.}} {{if IsString .}}is a string{{else}}is not a string{{end}}`))
fmt.Println(t.Execute(os.Stdout, "hi"))
fmt.Println(t.Execute(os.Stdout, 23))
这将输出(在 Go Playground 上尝试):
hi is a string<nil>
23 is not a string<nil>
(行尾的 <nil>
文字是模板执行返回的错误值,表明没有错误。)
使用printf
和 %T
动词
我们也可以在没有自定义函数的情况下执行此操作。有一个 printf
默认可用的函数,它是 fmt.Sprintf()
的别名.还有一个 %T
输出参数类型的动词。
想法是调用printf %T
值,并将结果与 "string"
进行比较,我们就完成了:
t := template.Must(template.New("").
Parse(`{{.}} {{if eq "string" (printf "%T" .)}}is a string{{else}}is not a string{{end}}`))
fmt.Println(t.Execute(os.Stdout, "hi"))
fmt.Println(t.Execute(os.Stdout, 23))
这也将输出(在 Go Playground 上尝试):
hi is a string<nil>
23 is not a string<nil>
关于string - 如何测试一个值是否是模板中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56091265/