Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Backfill Sprig functions in Liquid templating #34

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading