How to Truncate Strings in Golang Templates?

Mary-Kate Olsen
Release: 2024-11-10 13:21:02
Original
990 people have browsed it

How to Truncate Strings in Golang Templates?

Truncation of Strings in Golang Templates

In Golang HTML templates, there may arise a need to truncate text to fit within certain character limits. For example, you might want to limit the display of long content to prevent overcrowding or improve readability.

To achieve this truncation in templates, you can leverage the printf() function. It acts similarly to fmt.Sprintf and provides a convenient way to format strings. By utilizing printf() with the appropriate formatting argument, you can truncate strings to your desired length.

To illustrate this, let's consider an example:

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

In this example, printf() is used to format the string stored in .Content. The argument "%.25s" specifies that the result should be a string that is a maximum of 25 characters long. If .Content contains less than 25 characters, it will not be truncated. However, if .Content exceeds 25 characters, it will be cut off to fit within the 25-character limit.

You can also pass the truncation length as a separate integer argument to printf(). For example:

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

Here, the first argument "25" indicates that the resulting string should be a maximum of 25 characters long. Note that in both examples, the width and precision are measured in runes rather than bytes, as per the Golang documentation.

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