summaryrefslogtreecommitdiff
path: root/tmpl
diff options
context:
space:
mode:
authorDave Henderson <dhenderson@gmail.com>2022-04-09 16:36:58 -0400
committerDave Henderson <dhenderson@gmail.com>2022-04-10 15:27:15 -0400
commitae1620810cbd82eadd71abb51ba2fea97cf50a59 (patch)
treea907ef15a3959cf1ac7101ea1bc5becc038b6605 /tmpl
parent6c66d16b7ccb32636688c644b670141b5e5341aa (diff)
New tmpl.Path/tmpl.PathDir functions
Signed-off-by: Dave Henderson <dhenderson@gmail.com>
Diffstat (limited to 'tmpl')
-rw-r--r--tmpl/tmpl.go22
-rw-r--r--tmpl/tmpl_test.go33
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)
+}