eq 函数允许比较两个字符串是否相等
{{if eq .Name "MyName"}}
Run Code Online (Sandbox Code Playgroud)
有没有办法测试一个字符串是否以(或包含)另一个字符串结尾?
小智 6
funcs := map[string]any{
"contains": strings.Contains,
"hasPrefix": strings.HasPrefix,
"hasSuffix": strings.HasSuffix}
tmpl := `{{if hasSuffix . ".txt"}}yes!{{end}}`
t := template.Must(template.New("").Funcs(funcs).Parse(tmpl))
t.Execute(os.Stdout, "example.txt") // writes yes! to standard out
Run Code Online (Sandbox Code Playgroud)
一些使用 Go 模板作为功能的应用程序(例如 Hugo 和 Helm)默认提供这些功能。
(h/t 至 mkopriva)。