Truncation in Go Templates: A Guide
When working with HTML templates in Go, you may encounter the need to truncate text in order to display concise or character-limited content. This article delves into how to achieve string truncation using the 'printf' function within Go templates.
Using 'printf' for Truncation
Go templates provide the 'printf' function, analogous to 'fmt.Sprintf', allowing you to format and modify strings during template rendering. For truncation, you can use the following format:
{{ printf "%.25s" .Content }}
Here, '.Content' represents the string you want to truncate, and '%.25s' specifies that only the first 25 characters should be displayed. You can replace '25' with any desired maximum character length.
Passing Truncation Limit as Argument
Alternatively, you can pass the truncation limit as a separate integer argument to 'printf':
{{ printf "%.*s" 25 .Content }}
This ensures clearer template code by separating the truncation limit from the formatting string.
Unicode Code Point Units
It's important to note that 'printf' measures width and precision in units of Unicode code points, also known as runes. This differs from C's 'printf', where units are measured in bytes. Therefore, when specifying character limits, consider the Unicode code point count rather than the byte count.
The above is the detailed content of How to Truncate Strings in Go Templates with 'printf'?. For more information, please follow other related articles on the PHP Chinese website!