在Go模板中切片字符串

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

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.