From 1e745d950885a1aafa0a41b18c578e76722fe12d Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Fri, 15 May 2015 21:18:27 -0700 Subject: [PATCH] template/interpolate: user variables --- template/interpolate/funcs.go | 8 +++++-- template/interpolate/funcs_test.go | 34 ++++++++++++++++++++++++++++++ template/interpolate/i.go | 4 ++++ 3 files changed, 44 insertions(+), 2 deletions(-) diff --git a/template/interpolate/funcs.go b/template/interpolate/funcs.go index 8b081966c..68592e046 100644 --- a/template/interpolate/funcs.go +++ b/template/interpolate/funcs.go @@ -94,8 +94,12 @@ func funcGenTimestamp(ctx *Context) interface{} { } func funcGenUser(ctx *Context) interface{} { - return func() string { - return "" + return func(k string) string { + if ctx == nil || ctx.UserVariables == nil { + return "" + } + + return ctx.UserVariables[k] } } diff --git a/template/interpolate/funcs_test.go b/template/interpolate/funcs_test.go index 37dee1ad6..7afa53447 100644 --- a/template/interpolate/funcs_test.go +++ b/template/interpolate/funcs_test.go @@ -142,3 +142,37 @@ func TestFuncTimestamp(t *testing.T) { } } } + +func TestFuncUser(t *testing.T) { + cases := []struct { + Input string + Output string + }{ + { + `{{user "foo"}}`, + `foo`, + }, + + { + `{{user "what"}}`, + ``, + }, + } + + ctx := &Context{ + UserVariables: map[string]string{ + "foo": "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) + } + } +} diff --git a/template/interpolate/i.go b/template/interpolate/i.go index 68c60d95c..1033ad86a 100644 --- a/template/interpolate/i.go +++ b/template/interpolate/i.go @@ -11,6 +11,10 @@ type Context struct { // Data is the data for the template that is available Data interface{} + // UserVariables is the mapping of user variables that the + // "user" function reads from. + UserVariables map[string]string + // DisableEnv disables the env function DisableEnv bool }