58 lines
1.3 KiB
Go
58 lines
1.3 KiB
Go
package plugin
|
|
|
|
import (
|
|
"bytes"
|
|
|
|
"git.towk2.me/towk/configurator/pkg/storage"
|
|
"github.com/nikolalohinski/gonja/v2"
|
|
"github.com/nikolalohinski/gonja/v2/exec"
|
|
)
|
|
|
|
type Jinja2 struct{}
|
|
|
|
func (p *Jinja2) Name() string { return "jinja2" }
|
|
func (p *Jinja2) Version() string { return "test" }
|
|
func (p *Jinja2) Description() string { return "Renders Jinja 2 templates" }
|
|
func (p *Jinja2) Metadata() map[string]string {
|
|
return map[string]string{
|
|
"author.name": "David J. Allen",
|
|
"author.email": "davidallendj@gmail.com",
|
|
}
|
|
}
|
|
|
|
func (p *Jinja2) Init() error {
|
|
// nothing to initialize
|
|
return nil
|
|
}
|
|
|
|
func (p *Jinja2) Run(data storage.KVStore, args []string) error {
|
|
// render the files using Jinja 2 from args
|
|
newContent := []string{}
|
|
for _, arg := range args {
|
|
var (
|
|
context *exec.Context
|
|
template *exec.Template
|
|
output bytes.Buffer
|
|
err error
|
|
)
|
|
template, err = gonja.FromString(arg)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
context = exec.NewContext(data.GetData().(map[string]any))
|
|
if err = template.Execute(&output, context); err != nil { // Prints: Hello Bob!
|
|
panic(err)
|
|
}
|
|
newContent = append(newContent, output.String())
|
|
}
|
|
|
|
// write back to the data storage
|
|
data.Set("out", newContent)
|
|
return nil
|
|
}
|
|
|
|
func (p *Jinja2) Cleanup() error {
|
|
// nothing to clean up
|
|
return nil
|
|
}
|