Home > Backend Development > Golang > How to Truncate Strings in Go Templates?

How to Truncate Strings in Go Templates?

Patricia Arquette
Release: 2024-11-10 09:24:02
Original
438 people have browsed it

How to Truncate Strings in Go Templates?

Truncating Strings in Go Templates

When working with HTML templates in Go, you may encounter situations where you need to limit the length of a string. This can be useful for preventing text overflow or ensuring a consistent display.

In the example provided, you have a template that displays the contents of ".Content" in a range loop. By default, it will print the entire string. However, you wish to truncate it to a maximum of 25 characters.

The solution lies in utilizing printf within your template. This function allows you to manipulate strings in various ways, including truncation.

Using printf

To truncate a string in your template, you can use the printf directive with a format string specifying the desired length. For example:

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

This format string tells printf to format ".Content" as a string and limit its length to 25 characters. Any excess content beyond the first 25 characters will be discarded.

Dynamic Truncation

You can also dynamically specify the truncation length by passing the desired number as an additional argument to printf:

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

In this case, the first argument (25) represents the maximum length to truncate to. The second argument (".Content") is the string to be truncated.

Note on Precision

It's important to note that printf uses runes (Unicode code points) for measuring width and precision, rather than bytes. This means that multi-byte UTF-8 characters may be truncated in the middle. If you need byte-based truncation, consider using alternative approaches such as substring slicing.

The above is the detailed content of How to Truncate Strings in Go 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