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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.