如何截断Golang模板中的字符串

web*_*evy 22 go

在golang中,有没有办法在html模板中截断文本?

例如,我的模板中有以下内容:

{{ range .SomeContent }}
 ....
    {{ .Content }}
 ....

{{ end }
Run Code Online (Sandbox Code Playgroud)

{{ .Content }}产生:interdum et malesuada fames ac ante ipsum primis in faucibus.Aliquam tempus sem ipsum,vel accumsan felis vulputate id.Donec ultricies sem purus,non aliquam orci dignissim et.整数mi arcu.Pellentesque apsum quis velit venenatis vulputate vulputate ut enim.

我想将其减少到25个字符.

Ond*_*ták 37

您可以printf在模板中使用,模板充当fmt.Sprintf.在您的情况下,截断字符串将非常简单:

"{{ printf \"%.25s\" .Content }}"
Run Code Online (Sandbox Code Playgroud)


yum*_*kas 7

更新:现在,下面的代码符合unicode标准,适用于那些使用国际程序的人.

需要注意的一点是,下面的bytes.Runes("string")是一个O(N)操作,从符文到字符串的转换也是如此,因此这段代码在字符串上循环两次.为PreviewContent()执行以下代码可能更有效率

func (c ContentHolder) PreviewContent() string {
    var numRunes = 0
    for index, _ := range c.Content {
         numRunes++
         if numRunes > 25 {
              return c.Content[:index]
         }
    }
    return c.Content
}
Run Code Online (Sandbox Code Playgroud)

您可以选择此功能的选项.假设您有某种类型的内容持有者,可以使用以下内容:

type ContentHolder struct {
    Content string
    //other fields here
}

func (c ContentHolder) PreviewContent() string {
    // This cast is O(N)
    runes := bytes.Runes([]byte(c.Content))
    if len(runes) > 25 {
         return string(runes[:25])
    }
    return string(runes)
}
Run Code Online (Sandbox Code Playgroud)

然后你的模板将如下所示:

{{ range .SomeContent }}
....
{{ .PreviewContent }}
....
{{ end }}
Run Code Online (Sandbox Code Playgroud)

另一个选项是创建一个函数,该函数将接受字符串的前25个字符.代码看起来像这样(由@MartinDrLík修改代码,链接到代码)

package main
import (
    "html/template"
    "log"
    "os"
)

func main() {

    funcMap := template.FuncMap{

        // Now unicode compliant
        "truncate": func(s string) string {
             var numRunes = 0
             for index, _ := range s {
                 numRunes++
                 if numRunes > 25 {
                      return s[:index]
                 }
            }
            return s
       },
    }

    const templateText = `
    Start of text
    {{ range .}}
    Entry: {{.}}
    Truncated entry: {{truncate .}}
    {{end}}
    End of Text
    `
    infoForTemplate := []string{
        "Stackoverflow is incredibly awesome",
        "Lorem ipsum dolor imet",
        "Some more example text to prove a point about truncation",
        "??????????????????????????????????????????????????????",
    }

    tmpl, err := template.New("").Funcs(funcMap).Parse(templateText)
    if err != nil {
        log.Fatalf("parsing: %s", err)
    }

    err = tmpl.Execute(os.Stdout, infoForTemplate)
    if err != nil {
        log.Fatalf("execution: %s", err)
    }

}
Run Code Online (Sandbox Code Playgroud)

这输出:

Start of text

Entry: Stackoverflow is incredibly awesome
Truncated entry: Stackoverflow is incredib

Entry: Lorem ipsum dolor imet
Truncated entry: Lorem ipsum dolor imet

Entry: Some more example text to prove a point about truncation
Truncated entry: Some more example text to

Entry: ??????????????????????????????????????????????????????
Truncated entry: ?????????????????????????

End of Text
Run Code Online (Sandbox Code Playgroud)


fre*_*lys 6

您可以使用文档中的slice 。下面的示例必须工作:

    {{ slice .Content  0 25}}
Run Code Online (Sandbox Code Playgroud)