Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slice strings in Go templates

Tags:

go

How can I slice strings in a template using the text/template package? Of course, something like {{ $myString[0:5] }} is not working.

like image 413
TeknasVaruas Avatar asked Apr 17 '26 22:04

TeknasVaruas


1 Answers

Define your own slicing function with template.Funcs.

Code:

t.Funcs(template.FuncMap{
    "stringSlice": func(s string, i, j int) string {
        return s[i:j]
    }
})

Template:

{{ stringSlice .MyString 0 5 }}

See also: Template and custom function; panic: function not defined

PS: As @dyoo correctly noted in the comments; this minimal stringSlice function does nothing to prevent you from slicing UTF-8 characters in half. You should probably handle that in a live environment.

like image 195
thwd Avatar answered Apr 20 '26 13:04

thwd



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!