在Go模板中切割字符串。

huangapple go评论74阅读模式
英文:

Slice strings in Go templates

问题

你可以使用text/template包在模板中对字符串进行切片。当然,类似{{ $myString[0:5] }}这样的写法是无效的。

英文:

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

答案1

得分: 9

使用template.Funcs来定义自己的切片函数。

代码:

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

模板:

{{ stringSlice .MyString 0 5 }}

参考链接:https://stackoverflow.com/questions/17843311/template-and-custom-function-panic-function-not-defined

PS:正如评论中@dyoo正确指出的那样,这个简单的stringSlice函数无法防止将UTF-8字符切割成两半。在实际环境中,你可能需要处理这个问题。

英文:

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: https://stackoverflow.com/questions/17843311/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.

huangapple
  • 本文由 发表于 2014年9月24日 18:03:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/26014096.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定