/
template.go
66 lines (49 loc) · 1.43 KB
/
template.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
* @Author: 0xe8998e@gmail.com
* @Date: 2022-01-01 00:22:03
* @LastEditTime: 2022-01-28 16:44:06
* @LastEditors: 0xe8998e@gmail.com
* @FilePath: /gosible/pkg/gosible/gosible.go
* @Description: gosible Contol Servers of DevOps's Tool
*/
package gosible
import (
"io/ioutil"
"os"
"github.com/flosch/pongo2/v5"
"github.com/pkg/errors"
)
func TemplateString(template string, varsMap map[string]interface{}) (string, error) {
tpl, err := pongo2.FromString(template)
if err != nil {
return " ", errors.Wrap(err, "pongo2.FromString Error")
}
// Now you can render the template with the given
// pongo2.Context how often you want to.
ctxt := pongo2.Context{}
ctxt = ctxt.Update(varsMap)
out, err := tpl.Execute(ctxt)
if err != nil {
return " ", errors.Wrap(err, "tpl.Execute Error")
}
return out, nil
}
func TemplateFile(template string, varsMap map[string]interface{}) (string, error) {
tpl, err := pongo2.FromFile(template)
if err != nil {
return "", errors.Wrap(err, "pongo2.FromFile not found")
}
// context, _ := tpl.ExecuteBytes(pctx)
ctxt := pongo2.Context{}
ctxt = ctxt.Update(varsMap)
out, err := tpl.Execute(ctxt)
if err != nil {
return "", errors.Wrap(err, "tpl.Execute Error")
}
tmpFile, err := ioutil.TempFile(os.TempDir(), "gosible-")
if err != nil {
return "", errors.Wrap(err, "Cannot create temporary file")
}
ioutil.WriteFile(tmpFile.Name(), []byte(out), 0644)
return tmpFile.Name(), nil
}