Add regexp compile helper function for templates (#601)

## Tests
unit test
This commit is contained in:
shreyas-goenka 2023-07-25 16:42:53 +02:00 committed by GitHub
parent 8fdc0fec81
commit 47640b8b94
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 35 additions and 0 deletions

View File

@ -2,6 +2,7 @@ package template
import (
"fmt"
"regexp"
"text/template"
)
@ -17,4 +18,8 @@ var helperFuncs = template.FuncMap{
"fail": func(format string, args ...any) (any, error) {
return nil, ErrFail{fmt.Sprintf(format, args...)}
},
// Alias for https://pkg.go.dev/regexp#Compile. Allows usage of all methods of regexp.Regexp
"regexp": func(expr string) (*regexp.Regexp, error) {
return regexp.Compile(expr)
},
}

View File

@ -0,0 +1,25 @@
package template
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestTemplateRegexpCompileFunction(t *testing.T) {
ctx := context.Background()
tmpDir := t.TempDir()
r, err := newRenderer(ctx, nil, "./testdata/regexp-compile/template", "./testdata/regexp-compile/library", tmpDir)
require.NoError(t, err)
err = r.walk()
assert.NoError(t, err)
assert.Len(t, r.files, 1)
content := string(r.files[0].content)
assert.Contains(t, content, "0:food")
assert.Contains(t, content, "1:fool")
}

View File

@ -0,0 +1,5 @@
{{with (regexp "foo.?")}}
{{range $index, $element := (.FindAllString "seafood fool" -1) }}
{{print $index ":" $element}}
{{end}}
{{end}}