github.com/aspring/packer@v0.8.1-0.20150629211158-9db281ac0f89/template/interpolate/i.go (about) 1 package interpolate 2 3 import ( 4 "bytes" 5 "text/template" 6 ) 7 8 // Context is the context that an interpolation is done in. This defines 9 // things such as available variables. 10 type Context struct { 11 // Data is the data for the template that is available 12 Data interface{} 13 14 // Funcs are extra functions available in the template 15 Funcs map[string]interface{} 16 17 // UserVariables is the mapping of user variables that the 18 // "user" function reads from. 19 UserVariables map[string]string 20 21 // EnableEnv enables the env function 22 EnableEnv bool 23 24 // All the fields below are used for built-in functions. 25 // 26 // BuildName and BuildType are the name and type, respectively, 27 // of the builder being used. 28 // 29 // TemplatePath is the path to the template that this is being 30 // rendered within. 31 BuildName string 32 BuildType string 33 TemplatePath string 34 } 35 36 // Render is shorthand for constructing an I and calling Render. 37 func Render(v string, ctx *Context) (string, error) { 38 return (&I{Value: v}).Render(ctx) 39 } 40 41 // Validate is shorthand for constructing an I and calling Validate. 42 func Validate(v string, ctx *Context) error { 43 return (&I{Value: v}).Validate(ctx) 44 } 45 46 // I stands for "interpolation" and is the main interpolation struct 47 // in order to render values. 48 type I struct { 49 Value string 50 } 51 52 // Render renders the interpolation with the given context. 53 func (i *I) Render(ctx *Context) (string, error) { 54 tpl, err := i.template(ctx) 55 if err != nil { 56 return "", err 57 } 58 59 var result bytes.Buffer 60 var data interface{} 61 if ctx != nil { 62 data = ctx.Data 63 } 64 if err := tpl.Execute(&result, data); err != nil { 65 return "", err 66 } 67 68 return result.String(), nil 69 } 70 71 // Validate validates that the template is syntactically valid. 72 func (i *I) Validate(ctx *Context) error { 73 _, err := i.template(ctx) 74 return err 75 } 76 77 func (i *I) template(ctx *Context) (*template.Template, error) { 78 return template.New("root").Funcs(Funcs(ctx)).Parse(i.Value) 79 }