Skip to content

Commit

Permalink
tpl/collections: Add like operator to where function
Browse files Browse the repository at this point in the history
Closes #11279
  • Loading branch information
jmooring authored and bep committed Jul 28, 2023
1 parent dc2a544 commit f4598a0
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
35 changes: 35 additions & 0 deletions tpl/collections/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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>")
}
12 changes: 12 additions & 0 deletions tpl/collections/where.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"strings"

"github.com/gohugoio/hugo/common/hreflect"
"github.com/gohugoio/hugo/common/hstrings"
"github.com/gohugoio/hugo/common/maps"
)

Expand Down Expand Up @@ -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")
}
Expand Down

0 comments on commit f4598a0

Please sign in to comment.