In golang, is there a way to truncate text in an html template?
For example, I have the following in my template:
{{ range .SomeContent }}
....
Update: Now the code below is unicode compliant for those who are working with international programs.
One thing to note is that bytes.Runes("string") below is an O(N) operation, as is the converstion from runes to a string, so this code loops over the string twice. It is likely to be more efficient to do the code below for 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
}
You have a couple options for where this function can go. Assuming that you have some type of content holder, the below can be used:
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)
}
Then your template will look like this:
{{ range .SomeContent }}
....
{{ .PreviewContent }}
....
{{ end }}
The other option is to create a function that will take then first 25 characters of a string. The code for that looks like this (revision of code by @Martin DrLík, link to code)
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)
}
}
This outputs:
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