| 1 |
--- |
| 2 |
title: strings.Truncate |
| 3 |
description: Returns the given string, truncating it to a maximum length without cutting words or leaving unclosed HTML tags. |
| 4 |
categories: [] |
| 5 |
keywords: [] |
| 6 |
params: |
| 7 |
functions_and_methods: |
| 8 |
aliases: [truncate] |
| 9 |
returnType: template.HTML |
| 10 |
signatures: ['strings.Truncate SIZE [ELLIPSIS] INPUT'] |
| 11 |
aliases: [/functions/truncate] |
| 12 |
--- |
| 13 |
|
| 14 |
Since Go templates are HTML-aware, `truncate` will intelligently handle normal strings vs HTML strings: |
| 15 |
|
| 16 |
```go-html-template |
| 17 |
{{ "<em>Keep my HTML</em>" | safeHTML | truncate 10 }} → <em>Keep my …</em> |
| 18 |
``` |
| 19 |
|
| 20 |
> [!NOTE] |
| 21 |
> If you have a raw string that contains HTML tags you want to remain treated as HTML, you will need to convert the string to HTML using the [`safe.HTML`][] function before sending the value to `truncate`. Otherwise, the HTML tags will be escaped when passed through the `truncate` function. |
| 22 |
|
| 23 |
[`safe.HTML`]: /functions/safe/html/ |