【问题标题】:How to test if a value is a string in a template如何测试一个值是否是模板中的字符串
【发布时间】:2019-09-29 04:04:19
【问题描述】:

我想知道是否有可能以及如何测试一个值是否是 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 }}

这是我得到的错误

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

【问题讨论】:

  • 你想测试什么.Type?请出示minimal reproducible example
  • 这并不重要,因为此示例中的Type 只是一个值。
  • 这很重要,因为从它的名称来看,它看起来你将类型存储为reflect.Type 之类的东西,这将改变实现你想要的方式。

标签: string go types go-templates


【解决方案1】:

带有自定义函数

模板中没有预先声明的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>

(行尾的&lt;nil&gt;字面量是模板执行返回的错误值,表示没有错误。)

使用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>

【讨论】:

  • 在哪里注册这个功能?我正在编写一个传递给这个包gnorm.org 的go 模板。所以我不太清楚我会在哪里添加这段代码,以便我可以在上面引用的模板中使用它。
  • @brandNew 自定义函数必须在解析模板文本之前注册,因为模板引擎需要能够静态分析模板,并且它需要事先知道哪些字面量指定了有效的自定义函数。如果您无权访问模板来执行此操作,请使用不需要注册自定义函数的第二种方法(使用 printf 函数)。详情请见Using custom func in Go condition template
猜你喜欢
  • 1970-01-01
  • 2014-07-23
  • 2014-07-23
  • 1970-01-01
  • 2015-09-16
  • 1970-01-01
  • 2012-08-12
  • 2013-05-28
  • 2021-02-14
相关资源
最近更新 更多