-
-
Notifications
You must be signed in to change notification settings - Fork 8.1k
Add truncate template function #2882
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 5 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
a6caf55
Add truncate template function
biilmann ee61aab
Make truncate work with unicode
biilmann 0585b61
Handle self closing tags
biilmann a7ec4f3
Fix truncation edge case
biilmann 9496e95
Just 1 code branch for handling truncation
biilmann 5f30c36
Get rid of unecessary string cast
biilmann fdb12e6
Rewrite tag closing code for truncate
biilmann File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,156 @@ | ||
| // Copyright 2016 The Hugo Authors. All rights reserved. | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| package tpl | ||
|
|
||
| import ( | ||
| "errors" | ||
| "html" | ||
| "html/template" | ||
| "regexp" | ||
| "unicode" | ||
| "unicode/utf8" | ||
|
|
||
| "github.com/spf13/cast" | ||
| ) | ||
|
|
||
| var ( | ||
| tagRE = regexp.MustCompile(`^<(/)?([^ ]+?)(?:(\s*/)| .*?)?>`) | ||
| htmlSinglets = map[string]bool{ | ||
| "br": true, "col": true, "link": true, | ||
| "base": true, "img": true, "param": true, | ||
| "area": true, "hr": true, "input": true, | ||
| } | ||
| ) | ||
|
|
||
| type openTag struct { | ||
| name string | ||
| pos int | ||
| } | ||
|
|
||
| func truncate(a interface{}, options ...interface{}) (template.HTML, error) { | ||
| length, err := cast.ToIntE(a) | ||
| if err != nil { | ||
| return "", err | ||
| } | ||
| var textParam interface{} | ||
| var ellipsis template.HTML | ||
|
|
||
| switch len(options) { | ||
| case 0: | ||
| return "", errors.New("truncate requires a length and a string") | ||
| case 1: | ||
| textParam = options[0] | ||
| ellipsis = " …" | ||
| case 2: | ||
| textParam = options[1] | ||
| var ok bool | ||
| if ellipsis, ok = options[0].(template.HTML); !ok { | ||
| s, e := cast.ToStringE(options[0]) | ||
| if e != nil { | ||
| return "", errors.New("ellipsis must be a string") | ||
| } | ||
| ellipsis = template.HTML(html.EscapeString(s)) | ||
| } | ||
| default: | ||
| return "", errors.New("too many arguments passed to truncate") | ||
| } | ||
| if err != nil { | ||
| return "", errors.New("text to truncate must be a string") | ||
| } | ||
| text, err := cast.ToStringE(textParam) | ||
| if err != nil { | ||
| return "", errors.New("text must be a string") | ||
| } | ||
|
|
||
| _, isHTML := textParam.(template.HTML) | ||
|
|
||
| if utf8.RuneCountInString(text) <= length { | ||
| if isHTML { | ||
| return template.HTML(text), nil | ||
| } | ||
| return template.HTML(html.EscapeString(text)), nil | ||
| } | ||
|
|
||
| openTags := []openTag{} | ||
| var lastWordIndex, lastNonSpace, currentLen, endTextPos, nextTag int | ||
|
|
||
| for i, r := range text { | ||
| if i < nextTag { | ||
| continue | ||
| } | ||
|
|
||
| if isHTML { | ||
| // Make sure we keep tag of HTML tags | ||
| slice := string(text[i:]) | ||
|
||
| m := tagRE.FindStringSubmatchIndex(slice) | ||
| if len(m) > 0 && m[0] == 0 { | ||
| nextTag = i + m[1] | ||
| tagname := slice[m[4]:m[5]] | ||
| lastWordIndex = lastNonSpace | ||
| _, singlet := htmlSinglets[tagname] | ||
| if singlet || m[6] != -1 { | ||
| continue | ||
| } | ||
| if m[2] == -1 { | ||
| openTags = append(openTags, openTag{name: tagname, pos: i}) | ||
| } else { | ||
| // SGML: An end tag closes, back to the matching start tag, | ||
| // all unclosed intervening start tags with omitted end tags | ||
| for i, tag := range openTags { | ||
| if tag.name == tagname { | ||
| openTags = openTags[i:] | ||
| break | ||
| } | ||
| } | ||
| } | ||
| continue | ||
| } | ||
| } | ||
|
|
||
| currentLen++ | ||
| if unicode.IsSpace(r) { | ||
| lastWordIndex = lastNonSpace | ||
| } else if unicode.In(r, unicode.Han, unicode.Hangul, unicode.Hiragana, unicode.Katakana) { | ||
| lastWordIndex = i | ||
| } else { | ||
| lastNonSpace = i + utf8.RuneLen(r) | ||
| } | ||
|
|
||
| if currentLen > length { | ||
| if lastWordIndex == 0 { | ||
| endTextPos = i | ||
| } else { | ||
| endTextPos = lastWordIndex | ||
| } | ||
| out := text[0:endTextPos] | ||
| if isHTML { | ||
| // Close out any open HTML tags | ||
| out += string(ellipsis) | ||
| for _, tag := range openTags { | ||
| if tag.pos > endTextPos { | ||
| break | ||
| } | ||
| out += ("</" + tag.name + ">") | ||
| } | ||
| return template.HTML(out), nil | ||
| } | ||
| return template.HTML(html.EscapeString(out)) + ellipsis, nil | ||
| } | ||
| } | ||
|
|
||
| if isHTML { | ||
| return template.HTML(text), nil | ||
| } | ||
| return template.HTML(html.EscapeString(text)), nil | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| // Copyright 2016 The Hugo Authors. All rights reserved. | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| package tpl | ||
|
|
||
| import ( | ||
| "html/template" | ||
| "reflect" | ||
| "testing" | ||
| ) | ||
|
|
||
| func TestTruncate(t *testing.T) { | ||
| var err error | ||
| cases := []struct { | ||
| v1 interface{} | ||
| v2 interface{} | ||
| v3 interface{} | ||
| want interface{} | ||
| isErr bool | ||
| }{ | ||
| {10, "I am a test sentence", nil, template.HTML("I am a …"), false}, | ||
| {10, "", "I am a test sentence", template.HTML("I am a"), false}, | ||
| {10, "", "a b c d e f g h i j k", template.HTML("a b c d e"), false}, | ||
| {12, "", "<b>Should be escaped</b>", template.HTML("<b>Should be"), false}, | ||
| {10, template.HTML(" <a href='#'>Read more</a>"), "I am a test sentence", template.HTML("I am a <a href='#'>Read more</a>"), false}, | ||
| {20, template.HTML("I have a <a href='/markdown'>Markdown link</a> inside."), nil, template.HTML("I have a <a href='/markdown'>Markdown …</a>"), false}, | ||
| {10, "IamanextremelylongwordthatjustgoesonandonandonjusttoannoyyoualmostasifIwaswritteninGermanActuallyIbettheresagermanwordforthis", nil, template.HTML("Iamanextre …"), false}, | ||
| {10, template.HTML("<p>IamanextremelylongwordthatjustgoesonandonandonjusttoannoyyoualmostasifIwaswritteninGermanActuallyIbettheresagermanwordforthis</p>"), nil, template.HTML("<p>Iamanextre …</p>"), false}, | ||
| {13, template.HTML("With <a href=\"/markdown\">Markdown</a> inside."), nil, template.HTML("With <a href=\"/markdown\">Markdown …</a>"), false}, | ||
| {14, "Hello中国 Good 好的", nil, template.HTML("Hello中国 Good 好 …"), false}, | ||
| {15, "", template.HTML("A <br> tag that's not closed"), template.HTML("A <br> tag that's"), false}, | ||
| {14, template.HTML("<p>Hello中国 Good 好的</p>"), nil, template.HTML("<p>Hello中国 Good 好 …</p>"), false}, | ||
| {2, template.HTML("<p>P1</p><p>P2</p>"), nil, template.HTML("<p>P1 …</p>"), false}, | ||
| {10, nil, nil, template.HTML(""), true}, | ||
| {nil, nil, nil, template.HTML(""), true}, | ||
| } | ||
| for i, c := range cases { | ||
| var result template.HTML | ||
| if c.v2 == nil { | ||
| result, err = truncate(c.v1) | ||
| } else if c.v3 == nil { | ||
| result, err = truncate(c.v1, c.v2) | ||
| } else { | ||
| result, err = truncate(c.v1, c.v2, c.v3) | ||
| } | ||
|
|
||
| if c.isErr { | ||
| if err == nil { | ||
| t.Errorf("[%d] Slice didn't return an expected error", i) | ||
| } | ||
| } else { | ||
| if err != nil { | ||
| t.Errorf("[%d] failed: %s", i, err) | ||
| continue | ||
| } | ||
| if !reflect.DeepEqual(result, c.want) { | ||
| t.Errorf("[%d] got '%s' but expected '%s'", i, result, c.want) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // Too many arguments | ||
| _, err = truncate(10, " ...", "I am a test sentence", "wrong") | ||
| if err == nil { | ||
| t.Errorf("Should have errored") | ||
| } | ||
|
|
||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I would say:
Truncate a text to a max length without cutting words or leaving unclosed HTML tags. Since Go templates are HTML-aware,
truncatewill 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 thesafeHTMLtemplate function before sending the value totruncate; otherwise, the HTML tags will be escaped bytruncate.