Skip to content

Commit

Permalink
feat: Backfill Sprig functions in Liquid templating (#34)
Browse files Browse the repository at this point in the history
* backfill sprig functions in liquid templating

* exclude funcs without params

* restore internal functions

* update comment

* use lo contains function
  • Loading branch information
maciaszczykm authored Jun 7, 2024
1 parent a934832 commit 040559a
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 14 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,6 @@

# Dependency directories (remove the comment below to include it)
# vendor/

# IDE
.idea
47 changes: 33 additions & 14 deletions template/liquid.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,35 +5,54 @@ import (

"github.com/Masterminds/sprig/v3"
"github.com/osteele/liquid"
"github.com/samber/lo"
)

var (
liquidEngine = liquid.NewEngine()
sprigFunctions = map[string]string{
liquidEngine = liquid.NewEngine()

// excludedSprigFunctions contains names of Spring functions that will be excluded.
excludedSprigFunctions = []string{"hello", "now", "uuidv4"}

// sprigFunctionNameAliases contains additional aliases for Sprig functions.
sprigFunctionNameAliases = map[string]string{
"toJson": "to_json",
"fromJson": "from_json",
"b64enc": "b64enc",
"b64dec": "b64dec",
"semverCompare": "semver_compare",
"sha256sum": "sha26sum",
"quote": "quote",
"squote": "squote",
"replace": "replace",
"coalesce": "coalesce",
}

// internalFunctions to register. These will override Sprig functions if same names are used.
internalFunctions = map[string]any{
"indent": indent,
"nindent": nindent,
"replace": strings.ReplaceAll,
"default": dfault,
"ternary": ternary,
}
)

func init() {
fncs := sprig.TxtFuncMap()
for key, name := range sprigFunctions {

excludedFunctions := excludedSprigFunctions
for k := range internalFunctions {
excludedFunctions = append(excludedFunctions, k)
}

for name, fnc := range fncs {
if !lo.Contains(excludedFunctions, name) {
liquidEngine.RegisterFilter(name, fnc)
}
}

for key, name := range sprigFunctionNameAliases {
liquidEngine.RegisterFilter(name, fncs[key])
}
liquidEngine.RegisterFilter("indent", indent)
liquidEngine.RegisterFilter("nindent", nindent)
liquidEngine.RegisterFilter("replace", strings.ReplaceAll)

liquidEngine.RegisterFilter("default", dfault)
liquidEngine.RegisterFilter("ternary", ternary)
for name, fnc := range internalFunctions {
liquidEngine.RegisterFilter(name, fnc)
}
}

func RenderLiquid(input []byte, bindings map[string]interface{}) ([]byte, error) {
Expand Down

0 comments on commit 040559a

Please sign in to comment.