VirtusLab/render

Allow passing context to 'render' function

tsjnsn opened this issue · 5 comments

I have a shared template that I'd like to 'render' with different values, that way that template can be reusable:

values.yaml:

envVars:
  x: 123
  y: 456
other: 789

map-to-json.template:

{{- range $key, $value := . -}}
{{ $key | toJson }}: {{ $value | toJson }},
{{- end -}}

render output:

// current:
{{ readFile "map-to-json.template" | render }}
// "envVars": { "x": 123, "y": 456 },
// "other": "789",

// with optional context:
{{ readFile "map-to-json.template" | render .envVars }}
// "x": 123,
// "y": 456,

I'll have a look at implementing this, but I think there is a workaround.

If I understand correctly your use case, then you could do it like this:
config-global.yaml:

other: 789

config-1.yaml:

envVars:
  x: 123a
  y: 456a

config-2.yaml:

envVars:
  x: 123b
  y: 456b

map-to-json.template:

{{- range $key, $value := . -}}
{{ $key | toJson }}: {{ $value | toJson }},
{{- end -}}

main.template:

{{ readFile "map-to-json.template" | render }}
render --config config-global.yaml --config config-1.yaml --in main.template
render --config config-global.yaml --config config-2.yaml --in main.template

To clarify you question, I understand you'd rather do something like this:

config.yaml:

envVarsA:
  x: 123a
  y: 456a
envVarsB:
  x: 123b
  y: 456b

other: 789

map-to-json.template:

{{- range $key, $value := . -}}
{{ $key | toJson }}: {{ $value | toJson }},
{{- end -}}

main.template:

{{ readFile "map-to-json.template" | render .envVarsA }}
{{ readFile "map-to-json.template" | render .envVarsB }}
render --config config.yaml --in main.template

That last example is what I'm looking for. I can't do the workaround you've suggested since I need both values within in a single template.

I've committed the feature, will release a version soon.

Please let me know if you have any problems/see bugs in the new implementation.

Something might have slipped through the unit tests.