Home > Backend Development > Golang > How can I truncate strings in Golang templates?

How can I truncate strings in Golang templates?

Patricia Arquette
Release: 2024-11-15 01:42:02
Original
805 people have browsed it

How can I truncate strings in Golang templates?

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 }}
Copy after login

Currently, {{ .Content }} outputs a lengthy string:

At times et malesuada fames and ante ipsum primis in faucibus. Sometimes it's time to put it on itself, or it's a layer of felis vulputate. Until the ultricies I was pure, not some medical dignissim et. 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 }}
Copy after login

Alternatively, you can provide the truncation length as a separate integer argument to printf:

{{ printf "%.*s" 25 .Content }}
Copy after login

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.

The above is the detailed content of How can I truncate strings in Golang templates?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template