Go Template compare if string ends in or contains another string

Issue

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

Answered By – Bellingham Boss

Answer Checked By – Robin (GoLangFix Admin)

Leave a Reply

Your email address will not be published.