template/interpolate: add template_path

This commit is contained in:
Mitchell Hashimoto 2015-05-29 13:55:59 -07:00
parent 7ce76d2890
commit 2752e51e09
3 changed files with 48 additions and 6 deletions

View File

@ -23,12 +23,13 @@ func init() {
// Funcs are the interpolation funcs that are available within interpolations.
var FuncGens = map[string]FuncGenerator{
"env": funcGenEnv,
"isotime": funcGenIsotime,
"pwd": funcGenPwd,
"timestamp": funcGenTimestamp,
"uuid": funcGenUuid,
"user": funcGenUser,
"env": funcGenEnv,
"isotime": funcGenIsotime,
"pwd": funcGenPwd,
"template_path": funcGenTemplatePath,
"timestamp": funcGenTimestamp,
"uuid": funcGenUuid,
"user": funcGenUser,
"upper": funcGenPrimitive(strings.ToUpper),
"lower": funcGenPrimitive(strings.ToLower),
@ -92,6 +93,16 @@ func funcGenPwd(ctx *Context) interface{} {
}
}
func funcGenTemplatePath(ctx *Context) interface{} {
return func() (string, error) {
if ctx == nil || ctx.TemplatePath == "" {
return "", errors.New("template path not available")
}
return ctx.TemplatePath, nil
}
}
func funcGenTimestamp(ctx *Context) interface{} {
return func() string {
return strconv.FormatInt(InitTime.Unix(), 10)

View File

@ -116,6 +116,33 @@ func TestFuncPwd(t *testing.T) {
}
}
func TestFuncTemplatePath(t *testing.T) {
cases := []struct {
Input string
Output string
}{
{
`{{template_path}}`,
`foo`,
},
}
ctx := &Context{
TemplatePath: "foo",
}
for _, tc := range cases {
i := &I{Value: tc.Input}
result, err := i.Render(ctx)
if err != nil {
t.Fatalf("Input: %s\n\nerr: %s", tc.Input, err)
}
if result != tc.Output {
t.Fatalf("Input: %s\n\nGot: %s", tc.Input, result)
}
}
}
func TestFuncTimestamp(t *testing.T) {
expected := strconv.FormatInt(InitTime.Unix(), 10)

View File

@ -14,6 +14,10 @@ type Context struct {
// Funcs are extra functions available in the template
Funcs map[string]interface{}
// TemplatePath is the path to the template that this is being
// rendered within.
TemplatePath string
// UserVariables is the mapping of user variables that the
// "user" function reads from.
UserVariables map[string]string