Go 模板比较字符串是否以另一个字符串结尾或包含另一个字符串

Jon*_*hen 2 go go-templates

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