Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 790
Jonathan Chen Avatar asked Nov 15 '25 23:11

Jonathan Chen


1 Answers

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

like image 64
6 revsuser19310297 Avatar answered Nov 18 '25 19:11

6 revsuser19310297



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!