How to truncate a string in a Golang template

后端 未结 7 589
轮回少年
轮回少年 2021-01-01 09:16

In golang, is there a way to truncate text in an html template?

For example, I have the following in my template:

{{ range .SomeContent }}
 ....
             


        
7条回答
  •  时光取名叫无心
    2021-01-01 09:52

    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.


    Edit

    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.

提交回复
热议问题