VirtusLab / render

Universal data-driven template for generating textual output, as a static binary and a library
Apache License 2.0
141 stars 24 forks source link

Allow passing context to 'render' function #8

Closed tsjnsn closed 5 years ago

tsjnsn commented 5 years ago

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,
pawelprazak commented 5 years ago

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
pawelprazak commented 5 years ago

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
tsjnsn commented 5 years ago

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.

pawelprazak commented 5 years ago

I've drafted an implementation for the feature yesterday, but the template functions API is giving me a hard time. Stay tuned.

pon., 11 lut 2019, 05:16 użytkownik tsjnsn notifications@github.com napisał:

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.

— You are receiving this because you commented.

Reply to this email directly, view it on GitHub https://github.com/VirtusLab/render/issues/8#issuecomment-462215901, or mute the thread https://github.com/notifications/unsubscribe-auth/AAC-6j1ZAod48V9ryuh2W9NMnoYBnrlPks5vMO6xgaJpZM4ax5lX .

pawelprazak commented 5 years ago

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.