2015-05-16 00:05:47 -04:00
|
|
|
package interpolate
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"text/template"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Context is the context that an interpolation is done in. This defines
|
|
|
|
// things such as available variables.
|
|
|
|
type Context struct {
|
2015-05-16 00:08:46 -04:00
|
|
|
// Data is the data for the template that is available
|
|
|
|
Data interface{}
|
|
|
|
|
2015-05-16 00:18:27 -04:00
|
|
|
// UserVariables is the mapping of user variables that the
|
|
|
|
// "user" function reads from.
|
|
|
|
UserVariables map[string]string
|
|
|
|
|
2015-05-23 19:06:11 -04:00
|
|
|
// EnableEnv enables the env function
|
|
|
|
EnableEnv bool
|
2015-05-16 00:05:47 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// I stands for "interpolation" and is the main interpolation struct
|
|
|
|
// in order to render values.
|
|
|
|
type I struct {
|
|
|
|
Value string
|
|
|
|
}
|
|
|
|
|
|
|
|
// Render renders the interpolation with the given context.
|
|
|
|
func (i *I) Render(ctx *Context) (string, error) {
|
|
|
|
tpl, err := i.template(ctx)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
var result bytes.Buffer
|
2015-05-16 00:08:46 -04:00
|
|
|
var data interface{}
|
|
|
|
if ctx != nil {
|
|
|
|
data = ctx.Data
|
|
|
|
}
|
2015-05-16 00:05:47 -04:00
|
|
|
if err := tpl.Execute(&result, data); err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
return result.String(), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (i *I) template(ctx *Context) (*template.Template, error) {
|
|
|
|
return template.New("root").Funcs(Funcs(ctx)).Parse(i.Value)
|
|
|
|
}
|