英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论