]> git.maquefel.me Git - brevno-suite/hugo/commitdiff
tpl/collections: Add like operator to where function
authorJoe Mooring <joe.mooring@veriphor.com>
Thu, 22 Dec 2022 22:17:19 +0000 (14:17 -0800)
committerBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
Fri, 28 Jul 2023 07:53:00 +0000 (09:53 +0200)
Closes #11279

tpl/collections/integration_test.go
tpl/collections/where.go

index 7ef0b6c47c82f23202a3ae5960670abb1ed8e82a..a059bfd26bee2efdb66e58893591f5658cce0d8c 100644 (file)
@@ -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>")
+}
index 2904b7cdd4a92e38019e878ce5147faa0699b66b..07c2d3deb3bbb42f22a4dfec6d861505d2bd7e0e 100644 (file)
@@ -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")
        }