From 1f1c085faa1448b1713c081ad6320cfde35edeec Mon Sep 17 00:00:00 2001 From: Mathias Biilmann Date: Fri, 6 Jan 2017 01:42:32 -0800 Subject: [PATCH] tpl: Add truncate template function This commit adds a truncate template function for safely truncating text without breaking words. The truncate function is HTML aware, so if the input text is a template.HTML it will be truncated without leaving broken or unclosed HTML tags. {{ "this is a very long text" | truncate 10 " ..." }} {{ "With [Markdown](/markdown) inside." | markdownify | truncate 10 }} --- content/templates/functions.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/content/templates/functions.md b/content/templates/functions.md index 10be0f7de..7dc5f32fe 100644 --- a/content/templates/functions.md +++ b/content/templates/functions.md @@ -662,6 +662,16 @@ e.g. * `{{slicestr "BatMan" 3}}` → "Man" * `{{slicestr "BatMan" 0 3}}` → "Bat" +### truncate + +Truncate a text to a max length without cutting words or leaving unclosed HTML tags. Since Go templates are HTML-aware, truncate will handle normal strings vs HTML strings intelligently. It's important to note that if you have a raw string that contains HTML tags that you want treated as HTML, you will need to convert the string to HTML using the safeHTML template function before sending the value to truncate; otherwise, the HTML tags will be escaped by truncate. + +e.g. + +* `{{ "this is a text" | truncate 10 " ..." }}` → `this is a ...` +* `{{ "Keep my HTML" | safeHTML | truncate 10 }}` → `Keep my …` +* `{{ "With [Markdown](#markdown) inside." | markdownify | truncate 10 }}` → `With Markdown …` + ### split Split a string into substrings separated by a delimiter.