Add url parse helper function for templates (#600)

## Tests
unit test
This commit is contained in:
shreyas-goenka 2023-07-27 11:51:31 +02:00 committed by GitHub
parent 8ffff241fe
commit ed972f7ae0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 23 additions and 0 deletions

View File

@ -2,6 +2,7 @@ package template
import (
"fmt"
"net/url"
"regexp"
"text/template"
)
@ -18,6 +19,10 @@ 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/net/url#Parse. Allows usage of all methods of url.URL
"url": func(rawUrl string) (*url.URL, error) {
return url.Parse(rawUrl)
},
// 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

@ -39,3 +39,18 @@ func TestTemplateRegexpCompileFunction(t *testing.T) {
assert.Contains(t, content, "0:food")
assert.Contains(t, content, "1:fool")
}
func TestTemplateUrlFunction(t *testing.T) {
ctx := context.Background()
tmpDir := t.TempDir()
r, err := newRenderer(ctx, nil, "./testdata/urlparse-function/template", "./testdata/urlparse-function/library", tmpDir)
require.NoError(t, err)
err = r.walk()
assert.NoError(t, err)
assert.Len(t, r.files, 1)
assert.Equal(t, "https://www.databricks.com", string(r.files[0].content))
}

View File

@ -0,0 +1,3 @@
{{ with url "https://www.databricks.com/a/b?o=123#my-fragment" -}}
{{- print .Scheme `://` .Host -}}
{{- end -}}