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

[Feature] Handle with not existing keys #1948

Closed
xxxcoltxxx opened this issue Dec 19, 2023 · 4 comments
Closed

[Feature] Handle with not existing keys #1948

xxxcoltxxx opened this issue Dec 19, 2023 · 4 comments

Comments

@xxxcoltxxx
Copy link
Contributor

xxxcoltxxx commented Dec 19, 2023

Hello!
It would be nice to handle non-existing keys.
It will provide flexible control when working with non-existent keys and will make the template more readable.
It allows as to control where we should fallback to some default value and where we should fail template rendering.
Its easy to implement - just add command-line flag that controls the missingkey=error|zero option.

Current behavior:

$ gomplate -i 'Hi {{ .name }}'
Hi 14:06:57 ERR  error="failed to render template <arg>: template: <arg>:1:6: executing \"<arg>\" at <.name>: map has no entry for key \"name\""
$ gomplate -i 'Hi {{ if (has . "name") }}{{ .name }}{{ else }}Alex{{end}}'
Hi Alex

Proposed behavior:

$ gomplate --missing-key error -i 'Hi {{ .name }}'
Hi 14:06:57 ERR  error="failed to render template <arg>: template: <arg>:1:6: executing \"<arg>\" at <.name>: map has no entry for key \"name\""

$ gomplate --missing-key zero -i 'Hi {{ .name }}'
Hi <no value>

$ gomplate --missing-key zero -i 'Hi {{ .name | default "Alex" }}'
Hi Alex

$ gomplate --missingkey zero -i 'Hi {{ .name | required }}'
Hi 14:12:04 ERR  error="failed to render template <arg>: template: <arg>:1:11: executing \"<arg>\" at <required>: error calling required: can not render template: a required value was not set"
@hairyhenderson
Copy link
Owner

Hi @xxxcoltxxx, thanks for filing this and thanks for the PR.

This has come up before, in #310 and #1362 at least, and I think in other issues as well.

I'm not sure why a flag didn't occur to me for controlling it, but at this point it seems reasonable.

@gjrtimmer
Copy link

Is there any update on this? I hope this one makes it to a release soon, kinda need it.

@hairyhenderson
Copy link
Owner

@gjrtimmer thanks for prodding - the PR is stuck, I will unstick it.

As for a release, this will be in v4, which won't be "soon" (depending on what "soon" means to you). In the meantime, there are workarounds (the test namespace and coll.Has).

@hairyhenderson
Copy link
Owner

Fixed by #1949

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants