如何测试模板中的值是否为字符串

Siy*_*iya 5 string types go go-templates

我想知道是否可以,如果可以,如何测试一个值是否是 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 }}
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误

错误:解析 TablePaths 时出错:解析内容模板时出错:模板:templates/table.gotmpl:42:函数“IsString”未定义

icz*_*cza 5

具有自定义功能

模板中没有预先声明的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))
Run Code Online (Sandbox Code Playgroud)

这将输出(在Go Playground上尝试):

hi is a string<nil>
23 is not a string<nil>
Run Code Online (Sandbox Code Playgroud)

<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))
Run Code Online (Sandbox Code Playgroud)

这也会输出(在Go Playground上尝试一下):

hi is a string<nil>
23 is not a string<nil>
Run Code Online (Sandbox Code Playgroud)