diff options
author | Joe Mooring <joe.mooring@veriphor.com> | 2022-12-22 14:17:19 -0800 |
---|---|---|
committer | Bjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com> | 2023-07-28 09:53:00 +0200 |
commit | f4598a09864bee2689a7630dda83a71a9b9cf55b (patch) | |
tree | fa3ed0f1e4040e7292db2d966610527f01739373 /tpl | |
parent | dc2a544fac7a3f9cb8bff70d5cbe92b37dee98d1 (diff) |
tpl/collections: Add like operator to where function
Closes #11279
Diffstat (limited to 'tpl')
-rw-r--r-- | tpl/collections/integration_test.go | 35 | ||||
-rw-r--r-- | tpl/collections/where.go | 12 |
2 files changed, 47 insertions, 0 deletions
diff --git a/tpl/collections/integration_test.go b/tpl/collections/integration_test.go index 7ef0b6c47..a059bfd26 100644 --- a/tpl/collections/integration_test.go +++ b/tpl/collections/integration_test.go @@ -196,3 +196,38 @@ title: "p3" Home: p1|p3| `) } + +// Issue #11279 +func TestWhereLikeOperator(t *testing.T) { + t.Parallel() + files := ` +-- content/p1.md -- +--- +title: P1 +foo: ab +--- +-- content/p2.md -- +--- +title: P2 +foo: abc +--- +-- content/p3.md -- +--- +title: P3 +foo: bc +--- +-- layouts/index.html -- +<ul> + {{- range where site.RegularPages "Params.foo" "like" "^ab" -}} + <li>{{ .Title }}</li> + {{- end -}} +</ul> + ` + b := hugolib.NewIntegrationTestBuilder( + hugolib.IntegrationTestConfig{ + T: t, + TxtarString: files, + }, + ).Build() + b.AssertFileContent("public/index.html", "<ul><li>P1</li><li>P2</li></ul>") +} diff --git a/tpl/collections/where.go b/tpl/collections/where.go index 2904b7cdd..07c2d3deb 100644 --- a/tpl/collections/where.go +++ b/tpl/collections/where.go @@ -21,6 +21,7 @@ import ( "strings" "github.com/gohugoio/hugo/common/hreflect" + "github.com/gohugoio/hugo/common/hstrings" "github.com/gohugoio/hugo/common/maps" ) @@ -272,6 +273,17 @@ func (ns *Namespace) checkCondition(v, mv reflect.Value, op string) (bool, error return false, nil } return false, errors.New("invalid intersect values") + case "like": + if svp != nil && smvp != nil { + re, err := hstrings.GetOrCompileRegexp(*smvp) + if err != nil { + return false, err + } + if re.MatchString(*svp) { + return true, nil + } + return false, nil + } default: return false, errors.New("no such operator") } |