diff --git a/libs/template/helpers.go b/libs/template/helpers.go index 271fd539..342b3811 100644 --- a/libs/template/helpers.go +++ b/libs/template/helpers.go @@ -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) + }, } diff --git a/libs/template/helpers_test.go b/libs/template/helpers_test.go new file mode 100644 index 00000000..fbb66ae2 --- /dev/null +++ b/libs/template/helpers_test.go @@ -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") +} diff --git a/libs/template/testdata/regexp-compile/template/hello.tmpl b/libs/template/testdata/regexp-compile/template/hello.tmpl new file mode 100644 index 00000000..5ea55d79 --- /dev/null +++ b/libs/template/testdata/regexp-compile/template/hello.tmpl @@ -0,0 +1,5 @@ +{{with (regexp "foo.?")}} +{{range $index, $element := (.FindAllString "seafood fool" -1) }} +{{print $index ":" $element}} +{{end}} +{{end}}