AlecAivazis / survey

A golang library for building interactive and accessible prompts with full support for windows and posix terminals.
MIT License
4.07k stars 349 forks source link

Support configurable template data #491

Open masnax opened 11 months ago

masnax commented 11 months ago

When drawing a prompt, (say, multi select), a go template is used to determine what to render. Currently, the template string as well as additional template functions are exposed as global variables (here and here respectively). This is quite convenient as it allows for customization of the output, but the data passed into the template is internally specified, and can't be configured. It would be great if template data could be brought in line with the other template components and made to be configurable externally.

Currently, to get around this, it’s possible to use for.Sprintf to format the template with the data we want every time we want to draw it on the screen. This works, but is inefficient and can cause problems because the templates are cached.

Naively, this could be achieved by having a wrapper around the data passed to the template, and a configurable map[string]any:

var TemplateConfig = map[string]any{}

type templateData struct {
        Data any
        Config map[string]any
}
func RunTemplate(tmpl string, data interface{}) (string, string, error) {
        userBuf := bytes.NewBufferString("")
        tmplData := templateData{Data: data, Config: TemplateConfig}
        err = tPair[0].Execute(userBuf, tmplData)
        …

Any customization to the template can then be included in the global variable, without affecting the existing data to the template.