From 88aea56683ec1e469e97c0771c0c01a15010c7c2 Mon Sep 17 00:00:00 2001 From: Kazuo Oishi Date: Fri, 10 Oct 2025 13:05:07 +0900 Subject: [PATCH] tpl: Fix strings/truncate CJK handling Fix truncate position for mix of CJK and non-CJK text. Fixes #14039 --- tpl/strings/truncate.go | 6 +++++- tpl/strings/truncate_test.go | 13 +++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/tpl/strings/truncate.go b/tpl/strings/truncate.go index 727f57a0f..0a9f5c262 100644 --- a/tpl/strings/truncate.go +++ b/tpl/strings/truncate.go @@ -111,7 +111,11 @@ func (ns *Namespace) Truncate(s any, options ...any) (template.HTML, error) { if unicode.IsSpace(r) { lastWordIndex = lastNonSpace } else if unicode.In(r, unicode.Han, unicode.Hangul, unicode.Hiragana, unicode.Katakana) { - lastWordIndex = i + lastWordIndex = lastNonSpace + lastNonSpace = i + utf8.RuneLen(r) + if currentLen <= length { + lastWordIndex = lastNonSpace + } } else { lastNonSpace = i + utf8.RuneLen(r) } diff --git a/tpl/strings/truncate_test.go b/tpl/strings/truncate_test.go index d307d786d..633257456 100644 --- a/tpl/strings/truncate_test.go +++ b/tpl/strings/truncate_test.go @@ -41,6 +41,19 @@ func TestTruncate(t *testing.T) { {10, template.HTML("

IamanextremelylongwordthatjustgoesonandonandonjusttoannoyyoualmostasifIwaswritteninGermanActuallyIbettheresagermanwordforthis

"), nil, template.HTML("

Iamanextre …

"), false}, {13, template.HTML("With Markdown inside."), nil, template.HTML("With Markdown …"), false}, {14, "Hello中国 Good 好的", nil, template.HTML("Hello中国 Good 好 …"), false}, + {12, "", "日本語でHugoを使います", template.HTML("日本語でHugoを使いま"), false}, + {12, "", "日本語で Hugo を使います", template.HTML("日本語で Hugo を使"), false}, + {8, "", "日本語でHugoを使います", template.HTML("日本語でHugo"), false}, + {10, "", "日本語で Hugo を使います", template.HTML("日本語で Hugo"), false}, + {9, "", "日本語で Hugo を使います", template.HTML("日本語で Hugo"), false}, + {7, "", "日本語でHugoを使います", template.HTML("日本語で"), false}, + {7, "", "日本語で Hugo を使います", template.HTML("日本語で"), false}, + {6, "", "日本語でHugoを使います", template.HTML("日本語で"), false}, + {6, "", "日本語で Hugo を使います", template.HTML("日本語で"), false}, + {5, "", "日本語でHugoを使います", template.HTML("日本語で"), false}, + {5, "", "日本語で Hugo を使います", template.HTML("日本語で"), false}, + {4, "", "日本語でHugoを使います", template.HTML("日本語で"), false}, + {4, "", "日本語で Hugo を使います", template.HTML("日本語で"), false}, {15, "", template.HTML("A
tag that's not closed"), template.HTML("A
tag that's"), false}, {14, template.HTML("

Hello中国 Good 好的

"), nil, template.HTML("

Hello中国 Good 好 …

"), false}, {2, template.HTML("

P1

P2

"), nil, template.HTML("

P1 …

"), false}, -- 2.39.5