Search code examples
gogo-templates

Go Template compare if string ends in or contains another string


The eq function allows for comparing if two strings are equal

{{if eq .Name "MyName"}}

Is there a way to test if a string ends in (or contains) another string?


Solution

  • Use a function map containing the relevant string functions.

    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 the example on the playground.

    Some applications that use Go templates as a feature (Hugo and Helm are examples) provide these functions by default.

    (h/t to mkopriva).