lazy evaluation in ternary function? #1108
-
I wasn't able to determine from the documentation, but is there is way to setup a ternary function such that if the initial test condition is true, the false branch isn't actually evaluated unless that conditional executes? I'm using gomplate to render config templates inside a docker container, where the ternary condition first checks to see if an env var was populated and if not it does a lookup to AWS ParameterStore datasource. I'm observing that even if I provide all the values over env var, the ternary is checking parameter store anyways. In some cases such as automated testing I don't want it to touch parameter store at all.
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
The short answer to this is "no, not with Ultimately the problem is that in Go templates, all arguments are evaluated. In Go you could do something like So in the case of The general workaround for this is to just use {{- $http_port := "" }}
{{- if eq $env_http_port "" }}
{{- $http_port = (ds "smp" "/http-listen-port").Value }}
{{- else }}
{{- $http_port = $env_http_port }}
{{- end }} It's far more verbose, though. An alternate approach is to just assign to {{- $http_port := $env_http_port }}
{{- if eq $http_port "" }}
{{- $http_port = (ds "smp" "/http-listen-port").Value }}
{{- end }} You didn't ask about it, but the {{ defineDatasource "smp" (env.ExpandEnv "aws+smp:///${ENV}/myapp") }} So finally, here's a simpler version of your template that might be useful: {{ defineDatasource "smp" (env.ExpandEnv "aws+smp:///${ENV}/myapp") }}
{{- $http_port := env.Getenv "HTTP_LISTEN_PORT" }}
{{- if eq $http_port "" }}
{{- $http_port = (ds "smp" "/http-listen-port").Value }}
{{- end }} Hope that helps! |
Beta Was this translation helpful? Give feedback.
The short answer to this is "no, not with
ternary
" 😉Ultimately the problem is that in Go templates, all arguments are evaluated. In Go you could do something like
if cond1 || cond2
, andcond2
would only be evaluated ifcond1
first evaluated to false. But in thetext/template
language, all arguments to a function are evaluated first before calling the function.So in the case of
ternary
, or even the built-inor
function, all args must first be evaluated to booleans before the function itself is called.The general workaround for this is to just use
if
/else
blocks. In your case I think the following would work: