strings.Truncate
- Syntax
- strings.Truncate LENGTH [ELLIPSIS] STRING
- Returns
- any
- Alias
- truncate
Usage
The strings.Truncate function returns the given string, truncating it to a maximum length at a word boundary without leaving unclosed HTML tags. If STRING is longer than LENGTH characters, the function appends ELLIPSIS to the result. If you omit ELLIPSIS, the function appends a space followed by a horizontal ellipsis.
The return type depends on the types of STRING and ELLIPSIS. If either is of type template.HTML, the function returns template.HTML. Otherwise, it returns a string.
When truncating a value marked as safe HTML, such as one returned by the safe.HTML function, strings.Truncate closes any tag left open by the truncation instead of cutting in the middle of it.
If you have a raw string containing HTML tags that you want treated as HTML, convert it with the safe.HTML function first. Otherwise, strings.Truncate treats the tags as text, and Hugo escapes them when you print the result in an HTML template.
Examples
{{ "Hugo is a static site generator" | strings.Truncate 20 }} → Hugo is a static …
{{ "Hugo is a static site generator" | strings.Truncate 10 "..." }} → Hugo is a...Truncating a value marked as safe HTML:
{{ "<em>Keep my HTML</em>" | safeHTML | strings.Truncate 10 }} → <em>Keep my …</em>