In golang, is there a way to truncate text in an html template?
For example, I have the following in my template:
{{ range .SomeContent }}
....
Needs more magic for Unicode strings
This is not correct, see below
import "unicode/utf8"
func Short( s string, i int) string {
if len( s ) < i {
return s
}
if utf8.ValidString( s[:i] ) {
return s[:i]
}
// The omission.
// In reality, a rune can have 1-4 bytes width (not 1 or 2)
return s[:i+1] // or i-1
}
But i
above is not the number of chars. It's the number of bytes. Link to this code on play.golang.org
I hope this helps.
Updated: check string length. See @geoff comment below
See that answer, and play here. It's another solution.
package main
import "fmt"
func Short( s string, i int ) string {
runes := []rune( s )
if len( runes ) > i {
return string( runes[:i] )
}
return s
}
func main() {
fmt.Println( Short( "Hello World", 5 ) )
fmt.Println( Short( "Привет Мир", 5 ) )
}
But if you are interested in the length in bytes:
func truncateStrings(s string, n int) string {
if len(s) <= n {
return s
}
for !utf8.ValidString(s[:n]) {
n--
}
return s[:n]
}
play.golang.org. This function never panics (if n >= 0), but you can obtain an empty string play.golang.org
Also, keep in mind this experimental package golang.org/x/exp/utf8string
Package utf8string provides an efficient way to index strings by rune rather than by byte.