dongnaigu2052 2019-05-11 14:33
浏览 68

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

I would like to find out if it is possible and if so how, to test if a value is a string in a Go template.

I have tried the following with no success

{{- 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 }}

And this is the error that I get

Error: error parsing TablePaths: error parsing contents template: template: templates/table.gotmpl:42: function "IsString" not defined

  • 写回答

1条回答 默认 最新

  • dongmi4035 2019-05-11 15:30
    关注

    With a custom function

    There is no predeclared IsString() function available in templates, but we may easily register and use such a function:

    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))
    

    This will output (try it on the Go Playground):

    hi is a string<nil>
    23 is not a string<nil>
    

    (The <nil> literals at the end of lines are the error values returned by the template execution, telling there were no errors.)

    Using printf and %T verb

    We may also do this without custom functions. There is a printf function available by default, which is an alias for fmt.Sprintf(). And there is a %T verb which outputs the argument's type.

    The idea is to call printf %T on the value, and compare the result with "string", and we're done:

    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))
    

    This will also output (try it on the Go Playground):

    hi is a string<nil>
    23 is not a string<nil>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?