1
0
mirror of https://github.com/danog/liquid.git synced 2024-11-30 04:19:50 +01:00

Fix slice on multiline strings

This commit is contained in:
Daniil Gentili 2023-05-26 23:31:07 +02:00
parent e2740771b6
commit 0136a5a38d
Signed by: danog
GPG Key ID: 8C1BE3B34B230CA7
2 changed files with 11 additions and 5 deletions

View File

@ -12,7 +12,6 @@ import (
"strings"
"time"
"unicode"
"unicode/utf8"
"github.com/danog/liquid/values"
"github.com/osteele/tuesday"
@ -151,13 +150,16 @@ func AddStandardFilters(fd FilterDictionary) { // nolint: gocyclo
})
fd.AddFilter("sort_natural", sortNaturalFilter)
fd.AddFilter("slice", func(s string, start int, length func(int) int) string {
// runes aren't bytes; don't use slice
ss := []rune(s)
n := length(1)
if start < 0 {
start = utf8.RuneCountInString(s) + start
start = len(ss) + start
}
p := regexp.MustCompile(fmt.Sprintf(`^.{%d}(.{0,%d}).*$`, start, n))
return p.ReplaceAllString(s, "$1")
end := start+n
if end > len(ss) {
end = len(ss)
}
return string(ss[start:end])
})
fd.AddFilter("split", splitFilter)
fd.AddFilter("strip_html", func(s string) string {

View File

@ -98,8 +98,12 @@ var filterTests = []struct {
{`"I strained to see the train through the rain" | remove_first: "rain"`, "I sted to see the train through the rain"},
{`"Liquid" | slice: 0`, "L"},
{`"Liquid
Liquid" | slice: 0`, "L"},
{`"Liquid" | slice: 2`, "q"},
{`"Liquid" | slice: 2, 5`, "quid"},
{`"Liquid
Liquid" | slice: 2, 4`, "quid"},
{`"Liquid" | slice: -3, 2`, "ui"},
{`"a/b/c" | split: '/' | join: '-'`, "a-b-c"},