Case insensitive string compare in Go template

huangapple go评论91阅读模式
英文:

Case insensitive string compare in Go template

问题

Go模板提供了一个eq比较运算符,例如{{if eq .Var "val" }}

在这种情况下,如何进行不区分大小写的字符串比较最好?这样上述条件对于Var为"val"、"Val"或"VAL"都为真。

英文:

Go template provides an eq comparison operator, e.g., {{if eq .Var "val" }}.

What's the best way to do a case insensitive string comparison in this case? So that the above would be true for Var to be "val", "Val", or "VAL".

答案1

得分: 4

你可以简单地创建另一个小写变量s1 := strings.ToLower(s),然后将其与模板中的小写字符串进行比较。

英文:

You can simply create another lowercase variable s1 := strings.ToLower(s) and to compare it with your template against a lowercase string.

答案2

得分: 3

你可以使用template.Funcs()来注册你想在模板中使用的自定义函数。

有一个strings.EqualFold()函数可以执行字符串的不区分大小写比较。所以只需注册该函数,然后就可以在模板中调用它:

t := template.Must(template.New("").Funcs(template.FuncMap{
    "MyEq": strings.EqualFold,
}).Parse("{{.}} {{if MyEq . \"val\"}}匹配{{else}}不匹配{{end}} \"val\"."))

t.Execute(os.Stdout, "Val")
fmt.Println()
t.Execute(os.Stdout, "NotVal")

结果:

"Val" 匹配 "val".
"NotVal" 不匹配 "val".

Go Playground上试一试。

英文:

You can use template.Funcs() to register custom functions that you want to use in your templates.

There is a strings.EqualFold() function which performs case insensitive comparison of strings. So just register that function and you can call it from the template:

t := template.Must(template.New("").Funcs(template.FuncMap{
	"MyEq": strings.EqualFold,
}).Parse(`"{{.}}" {{if MyEq . "val"}}matches{{else}}doesn't match{{end}} "val".`))

t.Execute(os.Stdout, "Val")
fmt.Println()
t.Execute(os.Stdout, "NotVal")

Result:

"Val" matches "val".
"NotVal" doesn't match "val".

Try it on the Go Playground.

huangapple
  • 本文由 发表于 2015年7月28日 11:08:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/31666710.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定