Truncating Strings in Golang Templates
In Golang HTML templates, it is possible to truncate text displayed using the {{ .Content }} expression . For instance, consider the following template:
{{ range .SomeContent }} .... {{ .Content }} .... {{ end }}
Currently, {{ .Content }} outputs a lengthy string:
Sometimes hunger is noticed and before it is first in the throat. Sometimes it's time to put it on itself, or it's a layer of felis vulputate. Until the ultricies were pure, they did not have any medicinal value. The entire arc of my life. Pellentesque a ipsum quis velit venenatis vulputate vulputate ut enim.
To truncate this string to 25 characters, you can use printf within the template:
{{ printf "%.25s" .Content }}
Alternatively, you can provide the truncation length as a separate integer argument to printf:
{{ printf "%.*s" 25 .Content }}
Note that the truncation operation measures the length of the string in Unicode code points (runes), unlike the C printf function, which measures in bytes.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3