diff options
Diffstat (limited to 'tmpl')
| -rw-r--r-- | tmpl/tmpl.go | 22 | ||||
| -rw-r--r-- | tmpl/tmpl_test.go | 33 |
2 files changed, 52 insertions, 3 deletions
diff --git a/tmpl/tmpl.go b/tmpl/tmpl.go index e0c46c20..7021b72b 100644 --- a/tmpl/tmpl.go +++ b/tmpl/tmpl.go @@ -3,6 +3,7 @@ package tmpl import ( "bytes" + "path/filepath" "text/template" "github.com/pkg/errors" @@ -12,11 +13,28 @@ import ( type Template struct { root *template.Template defaultCtx interface{} + path string } // New - -func New(root *template.Template, ctx interface{}) *Template { - return &Template{root, ctx} +func New(root *template.Template, tctx interface{}, path string) *Template { + return &Template{root, tctx, path} +} + +// Path - returns the path to the current template if it came from a file. +// An empty string is returned for inline templates. +func (t *Template) Path() (string, error) { + return t.path, nil +} + +// PathDir - returns the directory of the template, if it came from a file. An empty +// string is returned for inline templates. If the template was loaded from the +// current working directory, "." is returned. +func (t *Template) PathDir() (string, error) { + if t.path == "" { + return "", nil + } + return filepath.Dir(t.path), nil } // Inline - a template function to do inline template processing diff --git a/tmpl/tmpl_test.go b/tmpl/tmpl_test.go index 729c99fb..7109a660 100644 --- a/tmpl/tmpl_test.go +++ b/tmpl/tmpl_test.go @@ -29,7 +29,7 @@ func TestInline(t *testing.T) { func TestParseArgs(t *testing.T) { defaultCtx := map[string]string{"hello": "world"} - tmpl := New(nil, defaultCtx) + tmpl := New(nil, defaultCtx, "") name, in, ctx, err := tmpl.parseArgs("foo") assert.NoError(t, err) assert.Equal(t, "<inline>", name) @@ -88,3 +88,34 @@ func TestExec(t *testing.T) { _, err = tmpl.Exec("bogus") assert.Error(t, err) } + +func TestPath(t *testing.T) { + tmpl := New(nil, nil, "") + + p, err := tmpl.Path() + assert.NoError(t, err) + assert.Equal(t, "", p) + + tmpl = New(nil, nil, "foo") + p, err = tmpl.Path() + assert.NoError(t, err) + assert.Equal(t, "foo", p) +} + +func TestPathDir(t *testing.T) { + tmpl := New(nil, nil, "") + + p, err := tmpl.PathDir() + assert.NoError(t, err) + assert.Equal(t, "", p) + + tmpl = New(nil, nil, "foo") + p, err = tmpl.PathDir() + assert.NoError(t, err) + assert.Equal(t, ".", p) + + tmpl = New(nil, nil, "foo/bar") + p, err = tmpl.PathDir() + assert.NoError(t, err) + assert.Equal(t, "foo", p) +} |
