You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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 }}
Copy file name to clipboardExpand all lines: docs/content/templates/functions.md
+9Lines changed: 9 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -662,6 +662,15 @@ e.g.
662
662
*`{{slicestr "BatMan" 3}}` → "Man"
663
663
*`{{slicestr "BatMan" 0 3}}` → "Bat"
664
664
665
+
### truncate
666
+
667
+
Truncate a text to a max length without cutting words or HTML tags in half. Since go templates are HTML aware, truncate will handle normal strings vs HTML strings intelligently.
668
+
669
+
e.q.
670
+
671
+
*`{{ "this is a text" | truncate 10 " ..." }}` → this is a ...
{10, "I am a test sentence", nil, template.HTML("I am a …"), false},
832
+
{10, "", "I am a test sentence", template.HTML("I am a"), false},
833
+
{10, "", "a b c d e f g h i j k", template.HTML("a b c d e"), false},
834
+
{12, "", "<b>Should be escaped</b>", template.HTML("<b>Should be"), false},
835
+
{10, template.HTML(" <a href='#'>Read more</a>"), "I am a test sentence", template.HTML("I am a <a href='#'>Read more</a>"), false},
836
+
{10, template.HTML("I have a <a href='/markdown'>Markdown</a> link inside."), nil, template.HTML("I have a <a href='/markdown'>Markdown …</a>"), false},
837
+
{10, nil, nil, template.HTML(""), true},
838
+
{nil, nil, nil, template.HTML(""), true},
839
+
}
840
+
fori, c:=rangecases {
841
+
varresult template.HTML
842
+
ifc.v2==nil {
843
+
result, err=truncate(c.v1)
844
+
} elseifc.v3==nil {
845
+
result, err=truncate(c.v1, c.v2)
846
+
} else {
847
+
result, err=truncate(c.v1, c.v2, c.v3)
848
+
}
849
+
850
+
ifc.isErr {
851
+
iferr==nil {
852
+
t.Errorf("[%d] Slice didn't return an expected error", i)
853
+
}
854
+
} else {
855
+
iferr!=nil {
856
+
t.Errorf("[%d] failed: %s", i, err)
857
+
continue
858
+
}
859
+
if!reflect.DeepEqual(result, c.want) {
860
+
t.Errorf("[%d] got '%s' but expected '%s'", i, result, c.want)
861
+
}
862
+
}
863
+
}
864
+
865
+
// Too many arguments
866
+
_, err=truncate(10, " ...", "I am a test sentence", "wrong")
0 commit comments