How to Truncate Strings in Go Templates with 'printf'?

Patricia Arquette
Release: 2024-11-14 10:05:02
Original
794 people have browsed it

How to Truncate Strings in Go Templates with 'printf'?

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

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

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!

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